【问题标题】:Android - Load image from gallery and set as backgroundAndroid - 从图库加载图像并设置为背景
【发布时间】:2016-02-20 11:57:06
【问题描述】:

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

这段代码可以正常工作:

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);
        }
    }
}

问题是我想将此信息存储在应用程序中,并且在用户关闭并重新打开应用程序后,我仍然希望拥有自定义背景图像。

我不知道如何存档。

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

如何得到预期的结果?

【问题讨论】:

    标签: android image background gallery


    【解决方案1】:

    将onActivityResult中的图像保存到存储中,然后将文件路径保存在SharedPreferences或数据库中...所以每次用户回来时,您都将其加载并设置为背景

    【讨论】:

      【解决方案2】:

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

      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>
      

      别忘了设置读写外部存储的权限

      【讨论】:

      • 我将上面的代码复制到名为'TestApp'的新项目中,我还在清单文件中添加了读写外部存储权限,代码不起作用。我已经转到设置->应用程序->TestApp(找到您的应用程序名称)。打开它,并授予它存储权限。现在,一切正常,谢谢!
      • 这是因为你使用的是android api高于棒棒糖的手机..它需要运行时权限..如果你为读写存储添加运行时权限,你不需要去外部设置,它只会在开始时询问..
      • 感谢您指出这一点。我听从了你的建议;在运行时设置权限,代码现在可以正常工作了。
      • 这对我不起作用,我已经复制了代码,并且在 Manifest 中我写了读写外部存储的权限,但它的图像没有显示在 activity_main 的视图中。
      猜你喜欢
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多