Android image compression

Source: Internet
Author: User

For a long time did not write a blog, recently busy graduation. In fact, I have always wanted to write a picture of the compression of the blog, blogging is actually to tidy up the knowledge and ideas I have learned as a record.

Image compression for Android is not only difficult in mobile development, it is not particularly easy to handle in any language. Generally divided into two kinds: size compression and quality compression, these two are the most common, in the app development process picture upload is very common, now the market is very high mobile phone pixels, such as vivo mobile phone a picture about 15M, which is too painful for users, upload a picture, This month's traffic will be gone, we can not do so, we have to compress the picture to a certain extent and then upload more appropriate. Here are two ways to compress pictures:

One, the size of the compression method one (according to the path of the picture compression):

/** * picture by Proportional size compression method (get picture and compress according to path) * * @param srcpath * @return */public static Bitmap getimage (String Srcpath) {Bitmapfactory.options newopts = new Bitmapfactory.options ();//start reading the picture, this time options.injustdecodebounds Set back to True newopts.injustdecodebounds = true; Bitmap Bitmap = Bitmapfactory.decodefile (Srcpath, newopts);//return Bitmap at this time Newopts.injustdecodebounds = false;int W = Newopts.outwidth;int h = newopts.outheight;//Now the mainstream phone is more 800*480 resolution, so the height and width we set to float hh = 800f;//Here Set the height to 800ffloat ww = 480 f;//set the width to 480f//zoom ratio here. Because it is a fixed scale, only one of the data of high or wide can be calculated by the int be = 1;//be=1 means not to scale if (W > H && w > ww) {//If the width is large then scale be = (int) According to the fixed width size OPTS.OUTWIDTH/WW);} else if (W < h && h > hh) {//If height is high, scale is = (int) (NEWOPTS.OUTHEIGHT/HH) According to the fixed width size;} if (be <= 0) is = 1;newopts.insamplesize = be;//Set scaling//Reread the picture, note that the options.injustdecodebounds has been set back to false bitmap = Bitm Apfactory.decodefile (Srcpath, newopts);//compress a good proportion of the size and then the quality compression return compressimage (bitmap);} 
Two, the size compression method two (according to the picture bitmap to compress):

/** * Picture by Proportional size compression method (compressed according to Bitmap picture) * * @param image * @return */public static Bitmap comp (Bitmap image) {Bytearrayoutputstre Am BAOs = new Bytearrayoutputstream () image.compress (Bitmap.CompressFormat.JPEG, BAOs);//Judging if the picture is greater than 1M, Compress to avoid overflow if (Baos.tobytearray () when generating picture (Bitmapfactory.decodestream). length/1024 > 1024) {//reset BAOs to Empty Baosbaos.reset ();//Here Compress 50%, the compressed data stored in the BAOs image.compress (Bitmap.CompressFormat.JPEG, BAOs);} Bytearrayinputstream ISBM = new Bytearrayinputstream (Baos.tobytearray ()); Bitmapfactory.options newopts = new Bitmapfactory.options ();//start reading the picture, this time options.injustdecodebounds Set back to True newopts.injustdecodebounds = true; Bitmap Bitmap = Bitmapfactory.decodestream (ISBM, NULL, newopts); newopts.injustdecodebounds = False;int W = Newopts.outwidth;int h = newopts.outheight;//Now the mainstream phone is more 800*480 resolution, so the height and width we set to float hh = 800f;//Here Set the height to 800ffloat ww = 480 f;//set the width to 480f//zoom ratio here. Because it is a fixed scale, only one of the data of high or wide can be calculated by the int be = 1;//be=1 is not scaled//if the width is large, the IF (W > H && w > ww) is scaled according to the width fixed sizebe = (int) (NEWOPTS.OUTWIDTH/WW);//If the height is high, it is scaled according to the width fixed size} else if (W < h && h > hh) {be = (int) (Newopts.outh EIGHT/HH);} if (be <= 0) is = 1;newopts.insamplesize = be;//Set scaling//Reread the picture, note that the options.injustdecodebounds has been set back to false ISBM = new by Tearrayinputstream (Baos.tobytearray ()); bitmap = Bitmapfactory.decodestream (ISBM, NULL, newopts);// Compress the proportions and then mass compress return Compressimage (bitmap);}
But sometimes the simple use of size compression does not compress to your own needs of memory size, and if the size of compression too large, will cause the picture distortion,you can see that the above code is compressed with a method called Compressimage (bitmap).This method is mass compression, combining size compression with mass compression, so the advantage is that the image will not be distorted after compression.

Third, the quality of the image compression (extracting some pixels)

/** * Image Quality compression *  * @param image * @return */public static Bitmap compressimage (Bitmap image) {Bytearrayoutputstream bao s = new Bytearrayoutputstream ();//Quality compression method, here 100 means no compression, the compressed data stored in the BAOs image.compress (Bitmap.CompressFormat.JPEG, 100, BAOS); int options = 100;//Loop Determines if the compressed image is greater than 100kb, which is greater than the continue compression while (Baos.tobytearray (). length/1024 > 100) {//Reset BAOs is empty BAOs Baos.reset ();//compress options% here and store the compressed data in BAOs image.compress (Bitmap.CompressFormat.JPEG, Options, BAOs);// 10options = 10 is reduced each time;} The compressed data BAOs stored in the bytearrayinputstream bytearrayinputstream ISBM = new Bytearrayinputstream (Baos.tobytearray ());// Generate picture of bytearrayinputstream data bitmap bitmap = Bitmapfactory.decodestream (ISBM, NULL, NULL); return bitmap;}
Below is the image processing tool Class I used, you can copy directly using:

Package Com.reduce_weight.utils;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.file;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import java.io.IOException; Import Java.util.date;import Android.annotation.suppresslint;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;public class Pictureutil {/** * Saves the bitmap bitmap to the path path * * @param bitmap */@SuppressLint (" Sdcardpath ") public static String Savebitmap (Bitmap Bitmap) {file FilePath = new File ("/sdcard/picture cache/"); Filepath.exists ()) {Filepath.mkdir ();} File File = new file ("/sdcard/picture Cache/", New Date (). GetTime () + "temp.png");//Create Files if (File.exists ()) {File.delete ();} try {fileoutputstream out = new FileOutputStream (file); bitmap.compress (Bitmap.CompressFormat.PNG, N, out); Out.flush ( ); Out.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return File.getabsolutepath ();} /** * Picture by Proportional size compression method (get picture according to path and compress) * * @parAm Srcpath * @return */public static Bitmap getimage (String srcpath) {bitmapfactory.options newopts = new Bitmapfactory.op tions ();//start reading into the picture, at this point Options.injustdecodebounds set back to True newopts.injustdecodebounds = true; Bitmap Bitmap = Bitmapfactory.decodefile (Srcpath, newopts);//return Bitmap at this time Newopts.injustdecodebounds = false;int W = Newopts.outwidth;int h = newopts.outheight;//Now the mainstream phone is more 800*480 resolution, so the height and width we set to float hh = 800f;//Here Set the height to 800ffloat ww = 480 f;//set the width to 480f//zoom ratio here. Because it is a fixed scale, only one of the data of high or wide can be calculated by the int be = 1;//be=1 means not to scale if (W > H && w > ww) {//If the width is large then scale be = (int) According to the fixed width size OPTS.OUTWIDTH/WW);} else if (W < h && h > hh) {//If height is high, scale is = (int) (NEWOPTS.OUTHEIGHT/HH) According to the fixed width size;} if (be <= 0) is = 1;newopts.insamplesize = be;//Set scaling//Reread the picture, note that the options.injustdecodebounds has been set back to false bitmap = Bitm Apfactory.decodefile (Srcpath, newopts);//compress a good proportion of the size and then the quality compression return compressimage (bitmap);} /** * Picture by Proportional size compression method (compressed according to bitmap picture) * * @param image * @return */public static BItmap Comp (Bitmap image) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); Image.compress ( Bitmap.CompressFormat.JPEG, BAOs);//Judging if the picture is larger than 1M, compress to avoid overflow if (the Bitmapfactory.decodestream) when the picture is generated Baos.tobytearray (). length/1024 > 1024) {//reset BAOs to Empty baosbaos.reset ();//compress 50% here and store the compressed data in BAOs image.compress ( Bitmap.CompressFormat.JPEG, BAOs);} Bytearrayinputstream ISBM = new Bytearrayinputstream (Baos.tobytearray ()); Bitmapfactory.options newopts = new Bitmapfactory.options ();//start reading the picture, this time options.injustdecodebounds Set back to True newopts.injustdecodebounds = true; Bitmap Bitmap = Bitmapfactory.decodestream (ISBM, NULL, newopts); newopts.injustdecodebounds = False;int W = Newopts.outwidth;int h = newopts.outheight;//Now the mainstream phone is more 800*480 resolution, so the height and width we set to float hh = 800f;//Here Set the height to 800ffloat ww = 480 f;//set the width to 480f//zoom ratio here. Because it is a fixed scale, only one of the data of high or wide can be calculated by the int be = 1;//be=1 means not to scale//if the width is large, the IF (W > H && w > ww) is scaled according to the width fixed size. {be = (int) (NEW OPTS.OUTWIDTH/WW);//If the height is high, scale according to the width fixed size} else if (W < h &Amp;& h > hh) {be = (int) (NEWOPTS.OUTHEIGHT/HH);} if (be <= 0) is = 1;newopts.insamplesize = be;//Set scaling//Reread the picture, note that the options.injustdecodebounds has been set back to false ISBM = new by Tearrayinputstream (Baos.tobytearray ()); bitmap = Bitmapfactory.decodestream (ISBM, NULL, newopts);// Compress the proportions and then mass compress return Compressimage (bitmap);}  /** * Image Quality Compression * * @param image * @return */public static Bitmap compressimage (Bitmap image) {Bytearrayoutputstream BAOs = New Bytearrayoutputstream ();//Quality compression method, here 100 means no compression, the compressed data stored in the BAOs image.compress (Bitmap.CompressFormat.JPEG, 100, BAOS); int options = 100;//Loop Determines if the compressed image is greater than 100kb, which is greater than the continue compression while (Baos.tobytearray (). length/1024 > 100) {//Reset BAOs is empty BAOs Baos.reset ();//compress options% here and store the compressed data in BAOs image.compress (Bitmap.CompressFormat.JPEG, Options, BAOs);// 10options = 10 is reduced each time;} The compressed data BAOs stored in the bytearrayinputstream bytearrayinputstream ISBM = new Bytearrayinputstream (Baos.tobytearray ());// Generate picture of bytearrayinputstream data bitmap bitmap = Bitmapfactory.decodestream (ISBM, Null, null); return bitmap;}} 
I used in the project is this way of compression, uploaded to the server are under 100K, and the picture is open or relatively clear, feel this compression method is still more reliable, if you have a good way to direct message tell me, we together learn.




Android image compression

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.