Android - 从图库加载图片并设置为背景

时间:2016-02-20 11:57:06

标签: android image background gallery

我想将图片库中的图片加载到我的应用中,并将此图片设置为背景。

这适用于此代码:

Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Select background"), SELECT_PICTURE);



public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();

            Drawable bg;
            try {
                InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
                bg = Drawable.createFromStream(inputStream, selectedImageUri.toString());
            } catch (FileNotFoundException e) {
                bg = ContextCompat.getDrawable(this, R.drawable.bg);
            }

            drawView.startNew();
            drawView.setBackground(bg);
        }
    }
}

问题是我想在app中存储这些信息,在用户关闭并重新打开应用程序后,我仍然想要自定义背景图像。

我不知道如何存档。

我尝试存储图像的Uri,但遇到一些权限问题(android.permission.MANAGE_DOCUMENTS),这是已知问题。

如何获得预期结果?

2 个答案:

答案 0 :(得分:1)

将图像保存在onActivityResult存储中,然后将文件路径保存在SharedPreference或数据库中...因此,每次用户返回时,都会将其加载并设置为背景

答案 1 :(得分:1)

在您的主要活动中使用此代码

public class MainActivity extends Activity {
    String mFilePath;
    private static int RESULT_LOAD_IMG = 1;
    String imgpath,storedpath;
    SharedPreferences sp;
    ImageView myImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         myImage = (ImageView) findViewById(R.id.imgView);
         sp=getSharedPreferences("setback", MODE_PRIVATE);
         if(sp.contains("imagepath")) {
             storedpath=sp.getString("imagepath", "");
             myImage.setImageBitmap(BitmapFactory.decodeFile(storedpath));
         }
    }
    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaColumns.DATA };

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgpath = cursor.getString(columnIndex);
                Log.d("path", imgpath);
                cursor.close();

            SharedPreferences.Editor edit=sp.edit();
                edit.putString("imagepath",imgpath);
                edit.commit();


                    Bitmap myBitmap = BitmapFactory.decodeFile(imgpath);

                    myImage.setImageBitmap(myBitmap);
            }
               else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }
}
}

这是你的布局xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ImageView>

    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:onClick="loadImagefromGallery"
        android:text="Load Picture" >
    </Button>

</LinearLayout>

不要忘记放置读写外部存储空间的权限