Pictures are available in various shapes and sizes. In many cases these pictures are much larger than our user interface (UI) and occupy a great deal of memory, and if we do not compress the bitmap, our program will have a memory leak error.
Mainactivity's Code
Package Com.example.g08_bitmap;import Android.os.bundle;import Android.app.activity;import Android.content.res.resources;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.widget.imageview;public class Mainactivity extends Activity {private ImageView ImageView; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); ImageView = (ImageView) This.findviewbyid (r.id.imageview1); Imageview.setimagebitmap ( Decodesampledbitmapfromresource (Getresources (), R.DRAWABLE.A, 300, 300));} public static Bitmap Decodesampledbitmapfromresource (Resources res,int resId, int reqwidth, int reqheight) {final BITMAPF Actory. Options options = new Bitmapfactory.options (),//First set Injustdecodebounds property to True, decoding avoids memory allocation options.injustdecodebounds = true;//the image into the selector Bitmapfactory.decoderesource (res, resId, options);//compress the picture at a specified scale options.insamplesize = Calculateinsamplesize (options, reqwidth,reqheight);//wait for the picture processing to be completed before the internalMemory leaks occur options.injustdecodebounds = False;return Bitmapfactory.decoderesource (res, resId, options);} Calculate the compressed proportions of a picture public static int calculateinsamplesize (bitmapfactory.options options,int reqwidth, int reqheight) {//Raw He ight and width of imagefinal int height = options.outheight;final int width = Options.outwidth;int Insamplesize = 1;if (He ight > Reqheight | | Width > Reqwidth) {final int heightratio = Math.Round ((float) height/(float) reqheight); final int widthRatio = math.ro und (float) width/(float) reqwidth);//Select a smaller ratio of length to width to become the compression ratio insamplesize = HeightRatio < WidthRatio? Heightratio:widthratio;} return insamplesize;}}