Task :- optimize image like Facebook and WhatApp does? Upload image to server with optimize size in android and ios without losing image quality and dimension.
I have seen many code like native image compression (UIImageJPEGRepresentation(viewImage, 0.8)) but I am not able to get proper result.
Can someone suggest me any algorithm or library in iOS and android through which we can optimise the image without losing quality.
Links I already visited:
iOS
Android
This is what I am using in Android :
public class ImageCompresser {
public static void compressImage(String inputFilePath, String outputFilePath) {
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(inputFilePath, options);
//options.inSampleSize = calculateInSampleSize(options,400,300);
options.inSampleSize = calculateInSampleSize(options,800,1000);//Specify Minimum Height, Width of the resulting bitmap maintaining the aspect ratio
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(inputFilePath, options);
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(outputFilePath);
ExifInterface exif;
try {
exif = new ExifInterface(inputFilePath);
Log.d("EXIF", "Make : " + exif.getAttribute(ExifInterface.TAG_MAKE));
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif Orientation : " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
Bitmap scaledBitmap = Bitmap.createBitmap(bm, 0, 0,
bm.getWidth(), bm.getHeight(), matrix,
true);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);//Instead of 100, you can provide any value. But it will reduce the image quality
scaledBitmap.recycle();
} catch (IOException e) {
e.printStackTrace();
}
fileOutputStream.flush();
fileOutputStream.close();
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int imageWidth = options.outWidth;
final int imageHeight = options.outHeight;
Log.d("Test", "imageWidth : " + imageWidth);
Log.d("Test", "imageHeight : " + imageHeight);
int inSampleSize = 1;
if(imageWidth > reqWidth || imageHeight > reqHeight) {
final int halfWidth = imageWidth / 2;
final int halfHeight = imageHeight / 2;
while((halfWidth / inSampleSize) > reqWidth
&& (halfHeight / inSampleSize) > reqHeight) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
References :