其他分享
首页 > 其他分享> > android-仅在Samsung Galaxy S4上运行时,ImageView无法通过setImageURI加载

android-仅在Samsung Galaxy S4上运行时,ImageView无法通过setImageURI加载

作者:互联网

在Samsung Galaxy S4(型号:GT-I9500)上运行一些基本代码时,我遇到了一个特定问题.

我当时是通过相机或图库实现图像选择器的,但我一生都无法弄清楚为什么在调用时ImageView是空白的-

imageView.setImageURI(uri);

直到我在模拟器(然后是Nexus 5)中运行完全相同的代码后,我才发现这是Samsung S4问题.

完整的示例项目可以在Github & ready to run上找到

我使用的代码来自此SO post

在OnCreate中:

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Choose Image Source");
            builder.setItems(new CharSequence[]{"Gallery", "Camera"},
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0:

                                    //Launching the gallery
                                    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(i, GALLERY);

                                    break;

                                case 1:
                                    //Specify a camera intent
                                    Intent getCameraImage = new Intent("android.media.action.IMAGE_CAPTURE");

                                    File cameraFolder;

                                    //Check to see if there is an SD card mounted
                                    if (android.os.Environment.getExternalStorageState().equals
                                            (android.os.Environment.MEDIA_MOUNTED))
                                        cameraFolder = new File(android.os.Environment.getExternalStorageDirectory(),
                                                IMAGEFOLDER);
                                    else
                                        cameraFolder = MainActivity.this.getCacheDir();
                                    if (!cameraFolder.exists())
                                        cameraFolder.mkdirs();

                                    //Appending timestamp to "picture_"
                                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
                                    String timeStamp = dateFormat.format(new Date());
                                    String imageFileName = "picture_" + timeStamp + ".jpg";

                                    File photo = new File(Environment.getExternalStorageDirectory(),
                                            IMAGEFOLDER + imageFileName);
                                    getCameraImage.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));

                                    //Setting a global variable to be used in the OnActivityResult
                                    imageURI = Uri.fromFile(photo);

                                    startActivityForResult(getCameraImage, CAMERA);

                                    break;
                                default:
                                    break;
                            }
                        }
                    });

            builder.show();
        }
    });

OnActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {


        switch (requestCode) {
            case GALLERY:
                Uri selectedImage = data.getData();
                imageView.setImageURI(selectedImage);

                break;
            case CAMERA:

                imageView.setImageURI(imageURI);
                break;
        }

    }

}

使用Picasso时也会发生

 if (resultCode == RESULT_OK) {


        switch (requestCode) {
            case GALLERY:
                Uri selectedImage = data.getData();
                Picasso.with(context)
                        .load(selectedImage)
                        .into(imageView);

                break;
            case CAMERA:
                Picasso.with(context)
                        .load(imageURI)
                        .into(imageView);
                break;
        }

    }

使用位图工厂时也会发生

  try {
                    Bitmap bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageURI));
                    imageView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

在运行4.2.2的Samsung S4上运行时的结果

在运行Android 4.4.4的GenyMotion 2.4.0上运行时的结果

有人知道为什么会这样吗?

解决方法:

因此问题出在三星S4无法处理的图像位图太大.

令人沮丧的是,不会引发任何错误-正确的解决方案如下:

switch (requestCode) {
            case GALLERY:
                Bitmap bitmap = createScaledBitmap(getImagePath(data, getApplicationContext()), imageView.getWidth(), imageView.getHeight());
                imageView.setImageBitmap(bitmap);
                break;
            case CAMERA:
                String path = imageURI.getPath();
                Bitmap bitmapCamera = createScaledBitmap(path, imageView.getWidth(), imageView.getHeight());
                imageView.setImageBitmap(bitmapCamera);
                break;
        }

辅助方法:

// Function to get image path from ImagePicker
public static String getImagePath(Intent data, Context context) {
    Uri selectedImage = data.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();
    return picturePath;
}


public Bitmap createScaledBitmap(String pathName, int width, int height) {
    final BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathName, opt);
    opt.inSampleSize = calculateBmpSampleSize(opt, width, height);
    opt.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(pathName, opt);
}

public int calculateBmpSampleSize(BitmapFactory.Options opt, int width, int height) {
    final int outHeight = opt.outHeight;
    final int outWidth = opt.outWidth;
    int sampleSize = 1;
    if (outHeight > height || outWidth > width) {
        final int heightRatio = Math.round((float) outHeight / (float) height);
        final int widthRatio = Math.round((float) outWidth / (float) width);
        sampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return sampleSize;
}

标签:onactivityresult,camera,imageview,gallery,android
来源: https://codeday.me/bug/20191028/1952150.html