android - 仅在三星 Galaxy S4 上运行时,ImageView 不会通过 setImageURI 加载

标签 android camera imageview gallery onactivityresult

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

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

imageView.setImageURI(uri);

直到我在模拟器(然后是 Nexus 5)中运行完全相同的代码,我才发现这是三星 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;
        }

    }

使用Bitmap Factory时也会出现

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

enter image description here

在运行 4.2.2 的三星 S4 上运行的结果

S4 Before S4 After

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

GenyMotion Before GenyMotion After

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

最佳答案

所以问题出在三星 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;
}

关于android - 仅在三星 Galaxy S4 上运行时,ImageView 不会通过 setImageURI 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29932060/

相关文章:

android - 如何打包我的 Android 库,以便我的客户不会遇到像 "AAPT: error: attribute layout_behavior"这样的错误

Android 辅助服务 - 清除 EditText

iPhone:获取相机预览

android - ScrollView 中的 ImageViews 导致延迟

java - 如何在圆形imageView android上添加阴影和边框?

android - 无法使用动态 attr drawable 膨胀 View

android - 尝试关闭相机 LED 时,应用程序崩溃

ios - 如何重置初始 ViewController 的状态?

android - 如何以编程方式多次更改 ImageView 源?

android - 在谷歌地图中绘制多边形线的 key 生成错误