Compress Image Android Studio

1. Create folder called Utils

2. Add class to that folder called CompressBitmap

3. Write inside that file the following:



import android.graphics.Bitmap;
import android.graphics.Matrix;

import java.io.ByteArrayOutputStream;

public class CompressBitmap {




public static Bitmap compress(Bitmap bitmap, double maxSize) {
// bitmapbitmap
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//
bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
byte[] b = baos.toByteArray();
// KB
double mid = b.length / 1024;
// bitmap
double i = mid / maxSize;
// bitmap
if (i > 1) {
//
//
bitmap = scale(bitmap, bitmap.getWidth() / Math.sqrt(i),
bitmap.getHeight() / Math.sqrt(i));
}

return bitmap;
}

public static Bitmap scale(Bitmap src, double newWidth, double newHeight) {
// src
float width = src.getWidth();
float height = src.getHeight();
// matrix
Matrix matrix = new Matrix();
//
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
//
matrix.postScale(scaleWidth, scaleHeight);
//
return Bitmap.createBitmap(src, 0, 0, (int) width, (int) height,
matrix, true);
}

public static Bitmap scale(Bitmap src, Matrix scaleMatrix) {
return Bitmap.createBitmap(src, 0, 0, src.getWidth(),
src.getHeight(), scaleMatrix, true);
}

public static Bitmap scale(Bitmap src, float scaleX, float scaleY) {
Matrix matrix = new Matrix();
matrix.postScale(scaleX, scaleY);
return Bitmap.createBitmap(src, 0, 0, src.getWidth(),
src.getHeight(), matrix, true);
}

public static Bitmap scale(Bitmap src, float scale) {
return scale(src, scale, scale);
}
}


4. Call this function to Compress

//-------------------------------------  COMPRESSING
Bitmap imageBitmap;
Bitmap imageBitmap2;
byte[] imageByte = new byte[0];
try {
imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

imageBitmap2 = compress(imageBitmap, 2000);

imageBitmap2.compress(Bitmap.CompressFormat.JPEG, 90, baos);
imageByte = baos.toByteArray();

} catch (IOException e) {
e.printStackTrace();
}

5. Original file will be compressed, so you can use the same filenamePath to access it

Comments

Popular posts from this blog

Android/Java: Crear un SplashScreen para nuestra aplicación

Android/Java: Video de fondo en nuestro Login

Android/Kotlin: Video de fondo en nuestro Login