Android bitmapfactory image compression processing (large bitmap Two-time sample compression processing)

Source: Internet
Author: User

In the actual development of Android, when loading a large number of images, such as Viewpager, GridView, listview, loading a large number of larger pictures will be prone to oom (memory overflow) exception, this is because the maximum memory usage of an application only 16M, If this value is exceeded, Oom will appear. Therefore, in our actual development, to avoid the occurrence of oom will be the corresponding image compression processing.

This article uses the bitmapfactory and the bitmapfactory.option these two classes, carries on the corresponding size compression processing to the picture. The oom exception that occurred before the uncompressed picture was successfully resolved by testing.

Realize:

This demo uses a picture size of about 2M (before compression).

Before I compress the picture:

I have commented out the compressed code here:


Operation Result:


To compress the image after processing:

The image size after compression is:


Approximately 98KB


Operation Result:


Source:


Layout file:

Activity_main:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">    <listview        android:id=" @+id/listview "        android:layout_width=" Match_parent "        android:layout_height= "wrap_content"        android:layout_alignparenttop= "true"        android:layout_ Centerhorizontal= "true" >    </ListView></RelativeLayout>

List_item.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "Horizontal" >    <imageview        android:id= "@+id/imageview" android:layout_width= "Wrap_        Content "        android:layout_height=" wrap_content "/>    <textview        android:id=" @+id/textview        " Android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"         android:layout_marginleft= " 20DP "/></linearlayout>


Mainactivity:

Package Com.android_bitmapcompressdemo;import Android.app.activity;import Android.os.bundle;import Android.widget.listview;public class Mainactivity extends Activity {private ListView listview;private Myadapter Adapter ;p rivate int[] items = new int[] {r.drawable.pc, r.drawable.pc,r.drawable.pc, r.drawable.pc, r.drawable.pc, R.DRAWABLE.P C,R.DRAWABLE.PC, r.drawable.pc, r.drawable.pc, r.drawable.pc,r.drawable.pc, r.drawable.pc, R.DRAWABLE.PC, R.DRAWABLE.PC,R.DRAWABLE.PC, r.drawable.pc, r.drawable.pc, r.drawable.pc,r.drawable.pc, R.DRAWABLE.PC, R.DRAWABLE.PC, r.drawable.pc,r.drawable.pc, r.drawable.pc, r.drawable.pc, R.DRAWABLE.PC,R.DRAWABLE.PC, R.DRAWABLE.PC, r.drawable.pc, r.drawable.pc,r.drawable.pc, r.drawable.pc, r.drawable.pc, R.DRAWABLE.PC, R.DRAWABLE.PC, r.drawable.pc}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); listview = (ListView) Findviewbyid (R.id.listview); adapter = new Myadapter (This,items); Listview.setadapter (adapter); adapter.notifydatasetchanged ();}} 


ListView Adapter: Myadapter:

Package Com.android_bitmapcompressdemo;import Android.content.context;import Android.graphics.bitmap;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.view.ViewGroup;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.textview;public class MyAdapter Extends Baseadapter {private int[] items = new int[] {};p rivate Context context;private String TAG = "Zhongyao";p rivate Bi TMap bitmap = Null;public Myadapter (context context, int[] items) {This.context = Context;this.items = items;} @Overridepublic int GetCount () {return items.length;} @Overridepublic Object getItem (int position) {return items[position];} @Overridepublic long Getitemid (int position) {return position;}  @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder;if (Convertview = = null) {Convertview = Layoutinflater.from (context). Inflate (R.layout.list_item, null); holder = new Viewholder (); Holder.imageview = (ImageView) Convertview.findviewbyid (r.id.imageview); Holder.textview = (TextView) Convertview.findviewbyid ( R.id.textview); Convertview.settag (holder);} else {holder = (Viewholder) Convertview.gettag ();} Bitmap = Bitmapcompresstools.decodesampledbitmapfromresource (Context.getresources (), r.drawable.pc, 100, 100); LOG.D (TAG, "image size after compression:" + bitmap.getbytecount ()); Holder.imageView.setImageBitmap (bitmap); Holder.textView.setText ("Picture" +position); return convertview;} Class Viewholder {ImageView ImageView; TextView TextView;}}

Bitmapcompresstools (Compression tool Class):

Package Com.android_bitmapcompressdemo;import Android.content.res.resources;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;public class Bitmapcompresstools {public static Bitmap Decodesampledbitmapfromresource (Resources res,int resId, int reqwidth, int reqheight) {//given bitmapfactory setting decoded parameter final Bitmapfactory.options Options = new Bitmapfactory.options ();//Get the width height of the original picture from the decoder, This avoids the direct application of memory space options.injustdecodebounds = true; Bitmapfactory.decoderesource (res, resId, options);//Calculate insamplesizeoptions.insamplesize = Calculateinsamplesize (options, reqwidth,reqheight);//The injustdecodebounds can be set to false after compression is complete. Options.injustdecodebounds = False;return Bitmapfactory.decoderesource (res, resId, options);} /** * Specify the scale of the picture * * @param options * @param reqwidth * @param reqheight * @return */public static int Calculateinsamplesi Ze (bitmapfactory.options options,int reqwidth, int reqheight) {//width of original picture, high final int height = options.outheight;final int W Idth = Options.outwidth;int InSAmplesize = 1;//if (height > Reqheight | | width > reqwidth) {////There are two kinds of compression options available. **//* Compression mode two//*/////final int halfheight = height/2;////final int halfwidth = width/2;////while ((Halfheight/ insamplesize) > reqheight////&& (halfwidth/insamplesize) > Reqwidth) {////insamplesize *= 2;////}///** * Compression mode one *///compute compression ratio: divided into a wide-high proportional final int heightratio = Math.Round ((float) height/(float) reqheight); final int widthRatio = Ma Th.round (float) width/(float) reqwidth); insamplesize = HeightRatio < WidthRatio? Heightratio:widthratio;//}return insamplesize;}}

To achieve the desired effect, but write here to slide the ListView, there will be some lag, there is a solution to this experience can give me a message to discuss.

The source code has been uploaded to the resource and can be downloaded to my resources.


Related Article

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.