在某些设备中拍摄照片android的OutOfMemeryError
作者:互联网
在某些设备和某些版本的Android中用相机拍照时,我遇到问题.例如,在我的Xperia U v4.0.3中,我的代码可以正常工作,但在另一个xperia U v2.3.3中,则无法正常工作…
我读到很多有关此错误的信息,但无法解决…
我拍摄照片并显示的代码:
public void callCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, SELECT_CAMERA);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_CAMERA) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
try {
imageSelected = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
// I tried to read the image created for the camera in the Sd
//But I've got the same error...
//imageSelected = Utils.readImageSD(this, selectedImage.getPath());
imageSelected = Utils.rotateImage(Utils.scaleBitmap(imageSelected, 160, 160));
ivImageLoad.setImageBitmap(imageSelected);
} catch (Exception e) {
Utils.showToast(getApplicationContext(), R.string.errorLoad);
Log.e("Camera", e.toString());
}
}
}
我希望有人能帮助我…我不知道该怎么办…
提前致谢.
问候.
解决方法:
看起来您只想显示一个160×160的位图,但是在这一行上,您正在读取整个位图,然后将其缩小.
imageSelected = android.provider.MediaStore.Images.Media(cr, selectedImage);
您可以避免使用inJustDecodeBounds将整个位图加载到内存中,然后可以使用inSampleSize对其进行缩放.
这是来自Loading Large Bitmaps Efficiently的Android系列的一些示例代码
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromUri(Uri uri,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
}
然后,获取160×160的图片,您只需执行以下操作:
ivImageLoad.setImageBitmap(decodeSampledBitmapFromUri(selectedImage, 100, 100));
标签:camera,out-of-memory,android 来源: https://codeday.me/bug/20191031/1977390.html