Сохранить рисунок в строку и преобразовать строку в растровое изображение из сохраненной строки? - PullRequest
0 голосов
/ 06 мая 2020

Пытаюсь сохранить темы. У меня есть темы (изображения) в папке drwable. Я показываю список изображений и, щелкая его, я хочу сохранить выбранный ресурс с возможностью рисования в общих настройках и получить то же самое из общих настроек.

Для этого я решил преобразовать ресурс с возможностью рисования в uri и преобразовать uri в строку.

Я попытался преобразовать drawable в uri, как показано ниже:

public static String getURLForResource (int resourceId,Context context) {


 //use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
    /*    return Uri
                .parse("android.resource://"+ BuildConfig.APPLICATION_ID  +
                        "/" +resourceId).toString();*/




    Resources resources = context.getResources();

    return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
            + resources.getResourcePackageName(resourceId) + '/'
            + resources.getResourceTypeName(resourceId) + '/'
            + resources.getResourceEntryName(resourceId)).toString();

}

, и извлек эту строку uri из sharedprefences и попытался преобразовать ее в растровое изображение:

     BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap =
                    BitmapFactory.decodeFile(sharedPreferencesData.getStr(
                            "ThemeName"),
                    options);*/
        /*        Uri myUri = Uri.parse(sharedPreferencesData.getStr(
                        "ThemeName"));

*/
         /*   Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));

            ContentResolver res = getContentResolver();
            InputStream in = null;
            try {
                in = res.openInputStream(uri);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Bitmap artwork = BitmapFactory.decodeStream(in);*/

            try {
                Uri uri = Uri.parse(sharedPreferencesData.getStr("ThemeName"));

                Bitmap bitmap =
                        MediaStore.Images.Media
                                .getBitmap(this.getContentResolver(), uri);

/*
                InputStream stream =
                        getAssets().open(sharedPreferencesData.getStr(
                                "ThemeName"));
                Drawable d = Drawable.createFromStream(stream, null);

                URL url_value = new URL(sharedPreferencesData.getStr(
                        "ThemeName").trim());

                    Bitmap mIcon1 =
                            BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
*/

Я пробовал несколько способов, ни один из них не работает. Либо растровое изображение пусто, либо я получаю исключение File not found и malformedException.

Помогите с тем же.

EDIT:

Я получаю следующую строку из getURLForResource :

D / ImageUri: android .resource: //com.dailyfaithapp.dailyfaith/drawable/theme0

Я создал класс с именем, шрифтом и т. Д. c ... и я устанавливаю такие же значения, как:

      public void setThemes(){


                Themes themes = new Themes();

                themes.setId(1);
   themes.setImage(Utils.getURLForResource(R.drawable.theme1,this));
                themes.setFont("AlexBrush-Regular.ttf");

                themesArrayList.add(themes);

                themes = new Themes();
                themes.setId(2);
            themes.setImage(Utils.getURLForResource(R.drawable.theme2,this));

                themes.setFont("SkinnyJeans.ttf");
                themesArrayList.add(themes);

                themes = new Themes();
                themes.setId(3);
themes.setImage(Utils.getURLForResource(R.drawable.theme3,this));
                themes.setFont("Roboto-Thin.ttf");
                themesArrayList.add(themes);

                themes = new Themes();
                themes.setId(4);
themes.setImage(Utils.getURLForResource(R.drawable.theme4,this));
                themes.setFont("Raleway-Light.ttf");
                themesArrayList.add(themes);
    }

1 Ответ

0 голосов
/ 07 мая 2020

вы можете использовать uri для рисования

    public static Drawable uriToDrawable(Uri uri) {


    Drawable d = null;

    try {
        InputStream inputStream;
        inputStream = G.context.getContentResolver().openInputStream(uri);
        d = Drawable.createFromStream(inputStream, uri.toString());
    } catch (FileNotFoundException e) {
        d = G.context.getResources().getDrawable(R.drawable.ic_launcher_background);
    }


    return d;
}

ИЛИ выполните следующие действия:

сохраните растровое изображение в приложении root и снова прочитайте

private void saveBitmap(Bitmap bitmap){
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
     // path to /data/data/yourapp/app_data/images
    File directory = cw.getDir("images", Context.MODE_PRIVATE);
    // Create imageDir
    File mypath=new File(directory,"bg.jpg");

    FileOutputStream fos = null;
    try {           
        fos = new FileOutputStream(mypath);

        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

    } catch (Exception e) {}
   }

Чтение растрового изображения

    private Bitmap readBitmap(String path)
    {

    try {
        File f=new File(path, "bg.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
        return b;
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }

  }
...