Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android位图从gallery压缩导致Xiomi手机OutOfMemory错误_Android_Bitmap_Out Of Memory_Android Imageview - Fatal编程技术网

Android位图从gallery压缩导致Xiomi手机OutOfMemory错误

Android位图从gallery压缩导致Xiomi手机OutOfMemory错误,android,bitmap,out-of-memory,android-imageview,Android,Bitmap,Out Of Memory,Android Imageview,下面的代码给出了当compress方法仅在Xiomi、华硕Zenfone2和三星S5设备中执行时的OutOfMemoryError Bitmap bm = BitmapFactory.decodeFile(<sd_card_path_here>); bm.compress(Bitmap.CompressFormat.JPEG, 20, out); Bitmap bm=BitmapFactory.decodeFile(); bm.compress(Bitmap.Compres

下面的代码给出了当compress方法仅在Xiomi、华硕Zenfone2和三星S5设备中执行时的OutOfMemoryError

  Bitmap bm = BitmapFactory.decodeFile(<sd_card_path_here>);
  bm.compress(Bitmap.CompressFormat.JPEG, 20, out);
Bitmap bm=BitmapFactory.decodeFile();
bm.compress(Bitmap.CompressFormat.JPEG,20,out);
目标sd卡路径有一个用0字节创建的文件


非常感谢您提供的任何帮助。

您应该高效地阅读加载位图,以便基本了解您可能遇到OutOfMemory异常的原因。 此外,处理位图应该在UI线程之外完成,以避免ANR错误

参考:
位图的宽度/高度是多少

Android的OpenGL版本限制每个位图4096*4096像素(65MB未压缩图像)

您还可以尝试增加AndroidManifest.xml中的应用程序内存

 <application ...
    android:largeHeap="true"..></application>

我从这里得到了工作答案:

    public String compressImage(String imageUri) {
 
        String filePath = getRealPathFromURI(imageUri);
        Bitmap scaledBitmap = null;
 
        BitmapFactory.Options options = new BitmapFactory.Options();
 
//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
 
        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;
 
//      max Height and width values of the compressed image is taken as 816x612
 
        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;
 
//      width and height values are set maintaining the aspect ratio of the image
 
        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {               imgRatio = maxHeight / actualHeight;                actualWidth = (int) (imgRatio * actualWidth);               actualHeight = (int) maxHeight;             } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;
 
            }
        }
 
//      setting inSampleSize value allows to load a scaled down version of the original image
 
        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
 
//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;
 
//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];
 
        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
 
        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }
 
        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;
 
        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
 
        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
 
//      check the rotation of the image and display it properly
        ExifInterface exif;
        try {
            exif = new ExifInterface(filePath);
 
            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        FileOutputStream out = null;
        String filename = getFilename();
        try {
            out = new FileOutputStream(filename);
 
//          write the compressed bitmap at the destination specified by filename.
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
 
        return filename;
 
    }


public String getFilename() {
    File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
    if (!file.exists()) {
        file.mkdirs();
    }
    String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
    return uriSting;
 
}


private String getRealPathFromURI(String contentURI) {
        Uri contentUri = Uri.parse(contentURI);
        Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
        if (cursor == null) {
            return contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(index);
        }
    }

public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
 
    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height/ (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;      }       final float totalPixels = width * height;       final float totalReqPixelsCap = reqWidth * reqHeight * 2;       while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }
 
    return inSampleSize;
}
公共字符串压缩图像(字符串图像URI){
 
字符串filePath=getRealPathFromURI(imageUri);
位图缩放位图=空;
 
BitmapFactory.Options Options=新的BitmapFactory.Options();
 
//通过将此字段设置为true,实际位图像素不会加载到内存中。只加载边界。如果
//如果您尝试在此处使用位图,将得到null。
options.inJustDecodeBounds=true;
位图bmp=BitmapFactory.decodeFile(文件路径,选项);
 
int实际高度=options.outHeight;
int actualWidth=options.outWidth;
 
//压缩图像的最大高度和宽度值为816x612
 
浮动最大高度=816.0f;
浮动最大宽度=612.0f;
浮动高度=实际宽度/实际高度;
浮点最大比值=最大宽度/最大高度;
 
//设置宽度和高度值以保持图像的纵横比
 
如果(实际高度>最大高度| |实际宽度>最大宽度){
if(imgRatiomaxRatio){
imgRatio=最大宽度/实际宽度;
实际高度=(int)(imgRatio*实际高度);
实际宽度=(int)最大宽度;
}其他{
实际高度=(int)最大高度;
实际宽度=(int)最大宽度;
 
            }
        }
 
//设置inSampleSize值允许加载原始图像的缩小版本
 
options.inSampleSize=calculateInSampleSize(选项、实际宽度、实际高度);
 
//inJustDecodeBounds设置为false以加载实际位图
options.inJustDecodeBounds=false;
 
//此选项允许android在内存不足时声明位图内存
options.inpurgable=true;
options.inInputShareable=true;
options.inTempStorage=新字节[16*1024];
 
试一试{
//从位图路径加载位图
bmp=BitmapFactory.decodeFile(文件路径,选项);
}catch(OutOfMemoryError异常){
异常。printStackTrace();
 
        }
试一试{
scaledbimat=Bitmap.createBitmap(实际宽度、实际高度、Bitmap.Config.ARGB_8888);
}catch(OutOfMemoryError异常){
异常。printStackTrace();
        }
 
浮动比率=实际宽度/(浮动)选项。向外宽度;
浮动比率=实际高度/(浮动)选项。超出高度;
浮动中间点x=实际宽度/2.0f;
浮动中间Y=实际高度/2.0f;
 
矩阵scaleMatrix=新矩阵();
scaleMatrix.setScale(ratioX、ratioY、middleX、middleY);
 
画布画布=新画布(缩放位图);
canvas.setMatrix(scaleMatrix);
drawBitmap(bmp,middleX-bmp.getWidth()/2,middleY-bmp.getHeight()/2,新绘制(Paint.FILTER_位图_标志));
 
//检查图像的旋转并正确显示
出口接口;
试一试{
exif=新的ExifInterface(文件路径);
 
int-orientation=exif.getAttributeInt(
ExiFinInterface.TAG_方向,0);
Log.d(“EXIF”,“EXIF:+方向”);
矩阵=新矩阵();
如果(方向==6){
矩阵旋转后(90);
Log.d(“EXIF”,“EXIF:+方向”);
}else if(方向==3){
矩阵旋转后(180);
Log.d(“EXIF”,“EXIF:+方向”);
}else if(方向==8){
矩阵旋转后(270);
Log.d(“EXIF”,“EXIF:+方向”);
            }
scaledBitmap=Bitmap.createBitmap(scaledBitmap,0,0,
scaledBitmap.getWidth(),scaledBitmap.getHeight(),矩阵,
正确的);
}捕获(IOE异常){
e.printStackTrace();
        }
 
FileOutputStream out=nul