简体   繁体   中英

Reduce image file size in Android (image type unknown)

I want to let the user choose how much they want to reduce the image file size by, could be low, medium or high then upload the image to a server That part is easy.

Next part is the actual reduction of file size. I'm getting the image URI, I want to reduce the file image file size, the image type could be png, jpg or something else.

I'm aware of Bitmap.compress() , is this the only way to implement or is there an existing open source library?

Bitmap bitmap;
bitmap = MyBitmapFactory.decodeFile(PATHTOPICT, UPLOAD_REQUIRED_SIZE);
if (bitmap != null) {
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

with the method (found with google):

public static Bitmap decodeFile(String filePath, final int REQUIRED_SIZE) {
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp <= REQUIRED_SIZE && height_tmp <= REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}

if something get NULL, its no image/ . scale by power 2 is recommended!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM