将图像文件从相机压缩到一定大小

ste*_*706 3 android memory-management bitmap android-bitmap

我正在尝试压缩我保存在文件中的图像.我正在尝试将文件压缩为1MB.我尝试了一些方法,但它通常会产生一个OutofMemoryError.然后我尝试使用此解决方案,但它使位图空白.

如何将位图从10mb图像从相机压缩到300kb beforw设置到android中的imageview

这是我的代码:

    System.gc();
    getActivity().getContentResolver().notifyChange(mImageTempUri, null);
    Bitmap bitmap;
    bitmap = BitmapFactory.decodeFile(mImageDirectory + mImageName, options);
    if(bitmap == null){
    howRequestFailedErrorMessage("Gambar gagal di-upload");
    return;

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();   


    bitmap.compress(Bitmap.CompressFormat.JPEG, 25, bytes);
    File f = new File(mImageDirectory + mImageName);
    if(f.exists()){
        f.delete();
    }
    FileOutputStream fo;

    try {
        fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        fo.flush();
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    bitmap.recycle();
Run Code Online (Sandbox Code Playgroud)

ste*_*706 9

好的,我得到了自己的答案

    File f = new File(mImageDirectory + mImageName);
    if(f.exists()){
        f.delete();
    }

    int MAX_IMAGE_SIZE = 1000 * 1024;
    int streamLength = MAX_IMAGE_SIZE;
    int compressQuality = 105;
    ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
    while (streamLength >= MAX_IMAGE_SIZE && compressQuality > 5) {
        try {
            bmpStream.flush();//to avoid out of memory error
            bmpStream.reset();
        } catch (IOException e) {
            e.printStackTrace();
        }
        compressQuality -= 5;
        bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
        byte[] bmpPicByteArray = bmpStream.toByteArray();
        streamLength = bmpPicByteArray.length;
        if(BuildConfig.DEBUG) {
            Log.d("test upload", "Quality: " + compressQuality);
            Log.d("test upload", "Size: " + streamLength);
        }
    }

    FileOutputStream fo;

    try {
        fo = new FileOutputStream(f);
        fo.write(bmpStream.toByteArray());
        fo.flush();
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)