I am trying to reduce the size of an image that a user has selected from the Gallery before passing it to another intent.
I am currently using the following code, but i
To Compress an Image you can use below code.
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageResizer {
public static String getCompressImageFile(File original, int width, int height, String filePath) {
Bitmap sampledSrcBitmap = decodeFile(original, width, height);
if(sampledSrcBitmap == null) {
return null;
}
Bitmap bitmap = getRotatedImage(sampledSrcBitmap,original.getPath());
int bitmap_width = bitmap.getWidth();
int bitmap_height = bitmap.getHeight();
boolean success;
if(bitmap_width reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public static boolean writeToFile(Bitmap image, File file, int quality) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(CompressFormat.JPEG, quality, bytes);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes.toByteArray());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
And to get compress Image path call getComressImagePath method and give selected gallery image path for compression. Pass the compress image path to next activity where you can use it to upload to the server.
public static String getComressImagePath(String picturePath){
//Here 720 is max width and 1280 is max height. you can set this as per your need. Lower the resolution smaller the image size.
return ImageResize.getCompressFile(new File(picturePath), 720, 1280, getTempImagePath());
}
public static String getTempImagePath(){
File root = new File(Environment.getExternalStorageDirectory() + File.separator + "IMAGES");
if (!root.exists()) {
root.mkdirs();
}
File image = null;
image = new File(root+File.separator+"fileName");
try {
image.createNewFile();
return image.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}