[Android algorithm] bitmap compress a picture to a specified size

Source: Internet
Author: User

Bitmap compressed to a specified size:

private void Imagezoom () {
Picture allows maximum space unit: KB
Double maxSize = 400.00;
Put bitmap in the array, intended to bitmap size (larger than the actual file being read)
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
Bitmap.compress (Bitmap.CompressFormat.JPEG, BAOs);
Byte[] B = Baos.tobytearray ();
Convert Bytes to kb
Double mid = b.length/1024;
Determine if the bitmap occupy space is greater than the allowable maximum space if the compression is less than the compressed
if (Mid > MaxSize) {
Gets how many times the bitmap size is allowed for the maximum size
Double i = mid/maxsize;
Start compression Here the square root is used to compress the width and height of the corresponding square root fold (1. Keep the scale and height consistent with the original bitmap ratio, and compress to the maximum size of the space)
BitMap = Zoomimage (BitMap, Bitmap.getwidth ()/math.sqrt (i),
Bitmap.getheight ()/math.sqrt (i));
}
}



public static Bitmap Zoomimage (Bitmap bgimage, double newwidth,
Double newheight) {
Get the width and height of this picture
Float width = bgimage.getwidth ();
float height = bgimage.getheight ();
Create a Matrix object for manipulating pictures
Matrix matrix = new Matrix ();
Calculate the wide and high zoom rate
float ScaleWidth = ((float) newwidth)/width;
float ScaleHeight = ((float) newheight)/height;
Zoom picture Action
Matrix.postscale (ScaleWidth, ScaleHeight);
Bitmap Bitmap = Bitmap.createbitmap (bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}

The compressed picture is larger than expected 10% reasons may be the width of the bitmap graph is inconsistent, resulting in compression error!

[Android algorithm] bitmap compress a picture to a specified size

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.