Compress image size

Asked

Viewed 1,483 times

2

How to compress the size of an image so that it is smaller ?

  public void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    thumbnail.compress(Bitmap.CompressFormat.JPEG, 85, bytes);
    byte[] b = bytes.toByteArray();
    String encodedfile = Base64.encodeToString(b, Base64.DEFAULT);


    base64p = encodedfile;


    System.out.println(base64p);


    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");
  • I don’t know in Java, but I use this service for this purpose. Even, they have an API that has an excellent compression result. If useful, please follow the link: https://tinypng.com.

  • Doubled his own question: Decrease a Base64

2 answers

0

Try using this library. It’s simple and easy to use.

Compressor

0

Try something similar to this:

    /**
 * Redimensiona a imagem.
 *
 * @return array de bytes com imagem redimensionada
 */
private static byte[] resizeImage(byte[] imageByte, int width, int height) throws IOException {
    try (InputStream inputImage = new ByteArrayInputStream(imageByte);) {
        BufferedImage image = ImageIO.read(inputImage);
        BufferedImage imgResized = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        imgResized.getGraphics().drawImage(image, 0, 0, width, height, null);
        return imageToByte(imgResized);
    }
}

Where imageToByte is this method:

    /**
 * Converte BufferedImage para array de bytes no formato JPG.
 *
 */
private static byte[] imageToByte(BufferedImage img) throws IOException {
    return imageToByte(img, ImageType.JPG);
}

imagesToByte:

    /**
 * Converte BufferedImage para array de bytes.
 *
 */
private static byte[] imageToByte(BufferedImage img, ImageType tipoImagem) throws IOException {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
        ImageIO.write(img, tipoImagem.getValue(), baos);
        baos.flush();
        return baos.toByteArray();
    }
}

The Enum he passes as a parameter is this:

public enum ImageType {
JPG("jpg"), PNG("png"), JPEG("jpeg");

This method works perfectly. Doubts I am available.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.