ImageView将不会加载通过setImageURI当运行在三星Galaxy S4只 [英] ImageView will not load via setImageURI when ran on Samsung Galaxy S4 Only

查看:364
本文介绍了ImageView将不会加载通过setImageURI当运行在三星Galaxy S4只的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我正在通过相机或图库实现图像选择器,并且不能为我的生活找出为什么ImageView在调用时为空白 -



imageView.setImageURI(uri);



我在模拟器中运行完全相同的代码(然后是Nexus 5),我发现这是一个三星S4问题。



完整的示例项目可以在< a href =https://github.com/AJ9/Samsung-S4-ImageView-Test =nofollow noreferrer> Github&准备运行



我使用的代码取自 SO post



OnCreate

b
$ b

  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 },
new DialogInterface.OnClickListener(){

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

//启动画廊
Intent i = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,GALLERY);

break;

case 1:
//指定摄像机意图
Intent getCameraImage = new Intent(android.media.action.IMAGE_CAPTURE);

文件cameraFolder;

//检查是否有一个SD卡装载
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();

//将时间戳附加到picture_
SimpleDateFormat dateFormat = new SimpleDateFormat(yyyyMMdd'T'HHmmss);
String timeStamp = dateFormat.format(new Date());
String imageFileName =picture_+ timeStamp +.jpg;

文件照片=新文件(Environment.getExternalStorageDirectory(),
IMAGEFOLDER + imageFileName);
getCameraImage.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));

//设置要在OnActivityResult中使用的全局变量
imageURI = Uri.fromFile(photo);

startActivityForResult(getCameraImage,CAMERA);

break;
默认值:
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();
}



在Samsung S4上运行4.2.2 p>




在GenyMotion 2.4上运行时的结果。 0运行Android 4.4.4






任何人都知道为什么会发生这种情况?

解决方案

所以问题出在图像位图太大, 。



令人沮丧的是没有错误发生 - 正确的解决方案如下:

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

辅助方法:

  //从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;
}


I've had a specific issue when running some basic code on a Samsung Galaxy S4 (model: GT-I9500).

I was implementing a image picker via the camera or gallery, and could not for the life of me figure out why the ImageView was blank when calling -

imageView.setImageURI(uri);

It wasn't until I ran the exact same code in the emulator (and then a Nexus 5) that I found that this was a Samsung S4 issue.

Full sample project can be found on Github & ready to run

Code I used was taken from this SO post:

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

    }

}

Also occurs when using 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;
        }

    }

Also occurs when using Bitmap Factory

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

The results when ran on a Samsung S4 running 4.2.2

The results when ran on a GenyMotion 2.4.0 running Android 4.4.4

Anyone know why this happens?

解决方案

So the problem turns out to be the image bitmaps being too large for the Samsung S4 to handle.

Frustratingly no errors are thrown - The correct solution is as follows:

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

Helper methods:

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

这篇关于ImageView将不会加载通过setImageURI当运行在三星Galaxy S4只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆