Ravi Malik
Ravi Malik

Reputation: 159

How to use different image compression on different imaze sizes in android

I want to compress images that i choose from gallery in android according to there sizes and upload them on to cloud storage. For example if size of an image which i choose is 300kb i don't to reduce it and keep quality 100 but if same is 7Mb i want to reduce it to 10 quality and i want to set max size to 7Mb of the chosen image(original without compression) and similarly puting different conditions on sizes in between.

My code

if (resultCode == RESULT_OK) {
    resultUri = result.getUri();

    File f = new File(resultUri.getPath());
    long sizeUri = f.length()/1024;

    try {
         bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(),resultUri));
    } catch (IOException e) {
        e.printStackTrace();
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    int baossize= baos.size()/1024;
    byte[] uploadbaos = baos.toByteArray();
    int lengthbmp = (uploadbaos.length);
    int size= lengthbmp/1024;

    Log.d(TAG,"baossize:  "+baossize+"   ByteArray: "+size+"  UriSize:  "+sizeUri);

    // UploadingImage();
}

Upvotes: 0

Views: 133

Answers (2)

rustyx
rustyx

Reputation: 85371

Just do it:

int quality;
if (sizeUri <= 300)
    quality = 90;
else if (sizeUri <= 1000)
    quality = 80;
else if (sizeUri <= 2000)
    quality = 70;
else if (sizeUri <= 3000)
    quality = 50;
else
    quality = 30;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

Note that JPEG quality 100 is probably too high and below 30 can be very blurry.

Upvotes: 1

Ravi
Ravi

Reputation: 2367

Here in the given example you can set the max size , like in your case it could be 7MB.

public static boolean reduceImage(String path, long maxSize) {
    File img = new File(path);
    boolean result = false;
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap = null;
    options.inSampleSize=1;
    while (img.length()>maxSize) {
        options.inSampleSize = options.inSampleSize+1;
        bitmap = BitmapFactory.decodeFile(path, options);
        img.delete();
        try
            {
                FileOutputStream fos = new FileOutputStream(path);
                img.compress(path.toLowerCase().endsWith("png")?
                                Bitmap.CompressFormat.PNG:
                                Bitmap.CompressFormat.JPEG, 100, fos);
                fos.close();
                result = true;
             }catch (Exception errVar) { 
                errVar.printStackTrace(); 
             }
    };
    return result;
}

Upvotes: 1

Related Questions