Skip to content Skip to sidebar Skip to footer

Reduce File Size Of An Image

I have taken a picture with the android camera. The result is an byte array. I save it by writing it on the sdcard (FileOutputStream). The result is an image with a filesize of nea

Solution 1:

I usually resize the image which reduces the size of it

Bitmapbitmap= resizeBitMapImage1(exsistingFileName, 800, 600);

You can also compress an image with this code

ByteArrayOutputStreambytes=newByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

//you can create a new file name "test.jpg" in sdcard folder.Filef=newFile(Environment.getExternalStorageDirectory()
                        + File.separator + "test.jpg")
f.createNewFile();
//write the bytes in fileFileOutputStreamfo=newFileOutputStream(f);
fo.write(bytes.toByteArray());

// remember close de FileOutput
fo.close();

Re-sizing Code

publicstatic Bitmap resizeBitMapImage1(String filePath, int targetWidth, int targetHeight) {
    Bitmap bitMapImage = null;
    try {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        double sampleSize = 0;
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth
                - targetWidth);
        if (options.outHeight * options.outWidth * 2 >= 1638) {
            sampleSize = scaleByHeight ? options.outHeight / targetHeight : options.outWidth / targetWidth;
            sampleSize = (int) Math.pow(2d, Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = BitmapFactory.decodeFile(filePath, options);
                break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {

                }
            }
        }
    } catch (Exception ex) {

    }
    return bitMapImage;
}

Post a Comment for "Reduce File Size Of An Image"