I am working on project where there is an need for image to be compressed and need get Uri for that compressed image. The problem is when I try to compress image from gallery it is creating one more image which is compressed along with the original image with different resolution how can achieve like I should have only one image reference in gallery that is also original image not the compressed image. Please find my code snippet below with which I have tried
public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
private static Bitmap rotateImage(Bitmap img, float degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
//img.recycle();
return rotatedImg;
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
public static Uri compressedImageUri(Uri selectedImage, Context context) {
try {
InputStream imageStream = null;
try {
imageStream = context.getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap original = BitmapFactory.decodeStream(imageStream);
//Bitmap bmp = getResizedBitmap(original, 500);
Bitmap rotateBitmap = rotateImageIfRequired(context, original, selectedImage);
Bitmap bmp = getResizedBitmap(rotateBitmap, 500);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, String.valueOf(System.currentTimeMillis()), null);
return Uri.parse(path);
} catch (Exception e) {
Log.d("error", e.getLocalizedMessage());
}
return null;
}
Use this Compressor.class
File imgFile = new File(uri.getPath());
File compressFile = Compressor.getDefault(getContext()).compressToFile(imgFile);
You may need some other class so please check compressor
package.
Hope this will help you.