A handy Android image compression Tool class

Source: Internet
Author: User

<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > used a long picture compression, before people have been using Google's official image compression method </span>

Final Bitmapfactory.options Options = new Bitmapfactory.options (); options.injustdecodebounds = true; Bitmapfactory.decoderesource (res, resId, options); options.insamplesize = calculateinsamplesize (options, Reqwidth, Reqheight); options.injustdecodebounds = False;return Bitmapfactory.decoderesource (res, resId, options);


public static int calculateinsamplesize (            bitmapfactory.options Options, int reqwidth, int reqheight) {    //Raw Hei Ght and width of image    final int height = options.outheight;    Final int width = options.outwidth;    int insamplesize = 1;    if (Height > Reqheight | | width > reqwidth) {        final int halfheight = HEIGHT/2;        Final int halfwidth = WIDTH/2;        Calculate the largest insamplesize value is a power of 2 and keeps both        //height and width larger than the RE quested height and width.        while ((halfheight/insamplesize) > Reqheight                && (halfwidth/insamplesize) > Reqwidth) {            Insamp Lesize *= 2;        }    }    return insamplesize;}

Code from Google

Http://developer.android.com/training/displaying-bitmaps/load-bitmap.html


Look closely at the Calucelateinsamplesize method, the algorithm returns a compression scale, carefully looking at his calculation process, you will find that the insamplesize change process is 2-4-8, while really into the Wile cycle, Wide high has been seen as a small half to calculate, so, the above site said 12M can be compressed to 0.75M, is because the gap is too big, if the Android phone internal compression of their own pictures (probably 2M compression to 100K), so at this time, this method applies to Android encoding compression.

So I'm compressing it for Android encoding, and it's optimized here, and the code is as follows:

Run: culculateinsamplesize (bm,200,300) Effect:

<pre name= "code" class= "java" ><span style= "font-family:arial, Helvetica, Sans-serif;" >/**</span>
* Calculate compression scale value (improved by touch_ping)
*
* Original 2>4>8 ... times compressed
* Current 2>3>4 ... times compression
*
* @param options
* Parse Image configuration information
* @param reqwidth
* Minimum width required for picture compression size
* @param reqheight
* Required image compression size min. height
* @return
*/
public static int Calculateinsamplesize (Bitmapfactory.options Options,
int reqwidth, int reqheight) {

Final int picheight = options.outheight;
Final int picwidth = Options.outwidth;
LOG.I ("Test", "Original size:" + picwidth + "*" +picheight);

int targetheight = Picheight;
int targetwidth = Picwidth;
int insamplesize = 1;

if (Targetheight > Reqheight | | targetwidth > Reqwidth) {
while (Targetheight >= reqheight
&& targetwidth>= reqwidth) {
LOG.I ("Test", "Compression:" +insamplesize + "Times");
Insamplesize + = 1;
Targetheight = picheight/insamplesize;
Targetwidth = picwidth/insamplesize;
}
}

LOG.I ("Test", "final compression ratio:" +insamplesize + "Times");
LOG.I ("Test", "New size:" + targetwidth + "*" +targetheight);
return insamplesize;
}


The compression effect is as follows:


File size changed from 1.12M to 81.75k



Finally, the complete compression tool class is attached:

Package Com.example.mqtest;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Android.content.res.resources;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import android.util.log;/** * Image Compression Tool class * @author touch_ping * 2015-1-5 pm 1:29:59 */public class Bitmapcompressor {/** * mass compression * @au Thor Ping 2015-1-5 pm 1:29:58 * @param image * @param maxkb * @return */public static Bitmap compressbitmap (Bitmap image,in T maxkb) {//l.showlog ("compressed picture"); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); Image.compress (Bitmap.CompressFormat.JPEG, BAOs);// Mass compression method, where 100 means no compression, the compressed data is stored in BAOs int options = 100;//LOG.I ("Test", "Original size" + Baos.tobytearray (). length); while ( Baos.tobytearray (). length/1024 > MAXKB) {//loop to determine if the picture is compressed after the image is greater than (MAXKB) 50kb, which is greater than continuing to compress//log.i ("Test", "compress once!"); Baos.reset ();//Reset BAOs is empty baosoptions-= 10;//each time reduce 10image.compress (Bitmap.CompressFormat.JPEG, Options, BAOs);// This compresses the options%, storing the compressed data in the BAOs}//log.i ("Test", "Compressed size" + Baos.tobytearray(). length); Bytearrayinputstream ISBM = new Bytearrayinputstream (Baos.tobytearray ());// The compressed data BAOs stored in the bytearrayinputstream bitmap bitmap = Bitmapfactory.decodestream (ISBM, NULL, NULL);// Generate a picture of the Bytearrayinputstream data return bitmap;} /** * http://developer.android.com/training/displaying-bitmaps/load-bitmap.html * Official website: Get compressed picture * * @param res * @param res ID * @param reqwidth * Required picture compression size min Width * @param reqheight * Required picture compression size min. Height * @return */public static BITM AP Decodesampledbitmapfromresource (Resources res,int resId, int reqwidth, int reqheight) {final bitmapfactory.options options = new Bitmapfactory.options (); options.injustdecodebounds = true; Bitmapfactory.decoderesource (res, resId, options); options.insamplesize = calculateinsamplesize (options, Reqwidth, Reqheight); options.injustdecodebounds = False;return Bitmapfactory.decoderesource (res, resId, options);}        /** * Official website: Get compressed picture * * @param res * @param resId * @param reqwidth * Required picture compression size minimum width * @param reqheight *    Required picture compression size min. Height * @return */public static Bitmap decodesampledbitmapfromfile (String filepath,int reqwidth, int reqheight) {Final Bitmapfactory.options Options = new Bitmapfactory.options (); options.injustdecodebounds = true; Bitmapfactory.decodefile (filepath, options); options.insamplesize = calculateinsamplesize (options, Reqwidth, Reqheight); options.injustdecodebounds = False;return bitmapfactory.decodefile (filepath, options);} public static Bitmap Decodesampledbitmapfrombitmap (Bitmap bitmap,int reqwidth, int reqheight) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); bitmap.compress (Bitmap.CompressFormat.PNG, N, BAOs); byte[] data = Baos.tobytearray (); final bitmapfactory.options Options = new Bitmapfactory.options (); options.injustdecodebounds = true; Bitmapfactory.decodebytearray (data, 0, data.length, options); options.insamplesize = calculateinsamplesize (Options, Reqwidth,reqheight); options.injustdecodebounds = False;return bitmapfactory.decodebytearray (data, 0, Data.length, OptiONS);}  /** * Calculate compression scale value (improved by touch_ping) * * Original 2>4>8 ... times compression * current 2>3>4 ... times compression * * @param options * Parse picture configuration information * @param reqwidth * Required picture compression size min. width o * @param reqheight * Required picture compression size min Height * @return */public static int C Alculateinsamplesize (bitmapfactory.options options,int reqwidth, int reqheight) {final int picheight = options.outheight;final int picwidth = options.outwidth; LOG.I ("Test", "Original size:" + picwidth + "*" +picheight); int targetheight = Picheight;int Targetwidth = Picwidth;int insamplesiz E = 1;if (targetheight > Reqheight | | targetwidth > Reqwidth) {while (Targetheight >= reqheight&& target width>= reqwidth) {log.i ("test", "Compression:" +insamplesize + "Times"); Insamplesize + = 1;targetheight = Picheight/insamplesize; Targetwidth = Picwidth/insamplesize;}} LOG.I ("Test", "final compression ratio:" +insamplesize + "Times"); LOG.I ("Test", "New size:" + targetwidth + "*" +targetheight); return insamplesize;}}








public static int calculateinsamplesize (            bitmapfactory.options Options, int reqwidth, int reqheight) {    //Raw Hei Ght and width of image    final int height = options.outheight;    Final int width = options.outwidth;    int insamplesize = 1;    if (Height > Reqheight | | width > reqwidth) {        final int halfheight = HEIGHT/2;        Final int halfwidth = WIDTH/2;        Calculate the largest insamplesize value is a power of 2 and keeps both        //height and width larger than the RE quested height and width.        while ((halfheight/insamplesize) > Reqheight                && (halfwidth/insamplesize) > Reqwidth) {            Insamp Lesize *= 2;        }    }    return insamplesize;}

A handy Android image compression Tool class

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.