setimagebitmap在api 23 android java中不起作用

pzfprimi  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(437)

我试图上传照片从画廊到我的应用程序与位图,在我的模拟器(api 22)它的工作,但由于某种原因,在我的手机(api 23)它不工作的图片不会显示只是一个空页。这是我的密码,如果有关系的话:

  1. public class Photoactivity extends Activity {
  2. private static final int SELECTED_PICTURE=1;
  3. ImageView iv;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_photoactivity);
  8. iv=(ImageView)findViewById(R.id.ImgView);
  9. }
  10. public void btnClick(View v){
  11. Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  12. startActivityForResult(i, SELECTED_PICTURE);
  13. }
  14. @Override
  15. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  16. // TODO Auto-generated method stub
  17. super.onActivityResult(requestCode, resultCode, data);
  18. switch (requestCode) {
  19. case SELECTED_PICTURE:
  20. if(resultCode==RESULT_OK){
  21. Uri selectedImage = data.getData();
  22. String[] filePathColumn = { MediaStore.Images.Media.DATA };
  23. Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
  24. cursor.moveToFirst();
  25. int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  26. String picturePath = cursor.getString(columnIndex);
  27. cursor.close();
  28. ImageView imageView = (ImageView) findViewById(R.id.ImgView);
  29. imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
  30. }
  31. break;
  32. default:
  33. break;
  34. }
  35. }

}

7gs2gvoe

7gs2gvoe1#

  1. image.setLayerType(View.LAYER_TYPE_SOFTWARE,null);

设置上述 layerType 在挣扎了一周后完成了魔术。

57hvy0tb

57hvy0tb2#

替换此项:

  1. case SELECTED_PICTURE:
  2. if(resultCode==RESULT_OK){
  3. Uri selectedImage = data.getData();
  4. String[] filePathColumn = { MediaStore.Images.Media.DATA };
  5. Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
  6. cursor.moveToFirst();
  7. int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  8. String picturePath = cursor.getString(columnIndex);
  9. cursor.close();
  10. ImageView imageView = (ImageView) findViewById(R.id.ImgView);
  11. imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
  12. }
  13. break;

有了这个:

  1. case SELECTED_PICTURE:
  2. if(resultCode==RESULT_OK){
  3. InputStream is=getContentResolver().openInputStream(data.getData());
  4. imageView.setImageBitmap(BitmapFactory.decodeStream(is));
  5. }
  6. break;

更好的是,切换到使用图像加载库,比如picasso,这样i/o就可以在后台线程上完成,这样在加载图像时就不会冻结ui。

展开查看全部
yk9xbfzb

yk9xbfzb3#

它确实有用。但不是以你的方式。在onactivityresult中检索图像时,使用uri查找其文件路径,然后对文件进行解码。问题是需要读取外部存储权限,而在api23中,您需要请求该权限。但你不必!您所需要做的就是通过解析流直接从uri获取位图。工作代码示例(也在api23上):

  1. Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(data.getData()));
  2. imageView.setImageBitmap(bitmap);

这样你就不会;我不需要访问文件。所以你不知道;读取外部存储器不需要权限。

相关问题