Long long ago, to the college to do an address book app needs to have an upload image function, pondering, racked up later still did not solve (student time things), so directly upload the original image, a picture 2M to 3M, so that my application after the release, it is definitely a traffic killer. Recently intentionally or unintentionally saw some of the image compression in Android article, now summed up to share with you.
Way One
I used this blog post at the end of the Android development bitmap to introduce bitmap image compression, but because of time is not explained, bitmap in the process of conversion into a stream can be compressed, if not compressed into some lossless compression format, such as PNG, We can compress the image into JPG format. As for how to get a bitmap object, please refer to the Android development bitmap use.
Look at the two lines of code, format to select non-PNG format can be compressed:
FileOutputStream out= new FileOutputStream (path +"456.gif");//0means to compress to a minimum, -means the best quality after compression, PNG is lossless image, will ignore this parameter//BP. Compress(Bitmap. Compressformat. JPEG, -, out);Bp. Compress(Bitmap. Compressformat. PNG,0, out); out. Flush(); out. Close();
This is done by using Bitmap's own method to compress, but after using it you will find that the quality of the image compressed by this way is actually very poor.
Way Two
To get a good picture of compression quality, we can use another way, in the bitmapfactory of several methods to get bitmap objects, almost every way to provide the option parameter, this parameter I also described in detail in the above:
inPreferredConfig 指定decode到内存中,手机中所采用的编码,可选值定义在Bitmap.Config中。缺省值是ARGB_8888。inJustDecodeBounds 如果设置为true,并不会把图像的数据完全解码,亦即decodeXyz()返回值为null,但是Options的outAbc中解出了图像的基本信息。inSampleSize 设置decode时的缩放比例。当值大于1时会对图像进行压缩,比如设置为4时,返回的图像宽高都将是原始图像的四分之一,像素是原始图像的十六分之一,如果设置的值小于1,则会被当作1来处理。注意,这里设值必须是2的次幂,其他值会被就近取离2的次幂最近的值。
So a new compression idea on the oven: first set Injustdecodebounds to True, get the basic information of the image, such as width and height, if the width of the image and tall in the target wide, then we reduce the width by the shift operation, until we want the value. Then, based on this value, set the value of the insamplesize so that you get a compressed image with less distortion.
Core code:
while(true) {if((Options.outwidth >> i <= -) && (options.outheight >> i <= -)) {inch=NewBufferedinputstream (NewFileInputStream (NewFile (path)); Options.insamplesize = (int) Math.pow (2.0D, i);//Power operation I for several partiesOptions.injustdecodebounds =false; Bitmap = Bitmapfactory.decodestream (inch,NULL, options); Break; } i + =1; }
This article full code download
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If there is a wrong place, I would appreciate it if I could criticize it.
Also talk about Android development image compression