In Android development, we often encounter the Android read image size more than the screen display map (generally as long as a certain size of the preview can be shown), in the picture is particularly large or the picture appears very often to pay special attention to this problem, the following describes a specified size to read the image method.
Implementation principle: First get picture file image high and wide, if less than the specified ratio, then read directly; If the ratio is exceeded, compress the read by the specified proportions.
Attention points when capturing OutOfMemoryError: The return is null, do not immediately read from other places, including the R file, or you will still throw this exception, usually in the initialization of the default image cache, and then display the picture in the cache.
/** get the width and height of the image **/
public static int[] GETIMAGEWH (String path) {int[] wh = {-1,-1};
if (path = = null) {return WH;
File File = new file (path); if (file.exists () &&!file.isdirectory ()) {try {bitmapfactory.options Options = new Bitmapfactory.options ()
;
Options.injustdecodebounds = true;
InputStream is = new FileInputStream (path);
Bitmapfactory.decodestream (IS, null, options);
Wh[0] = options.outwidth;
WH[1] = options.outheight;
catch (Exception e) {LOG.W (TAG, "Getimagewh Exception.", e);
} return WH;
public static Bitmap Createbitmapbyscale (String path, int scale) {BITMAP BM = null;
try {//Get width high int[] wh = GETIMAGEWH (path);
if (wh[0] = =-1 | | wh[1] = = 1) {return null;
//Read picture bitmapfactory.options Options = new Bitmapfactory.options ();
Options.insamplesize = Math.max (Wh[0]/scale, Wh[1]/scale);
InputStream is = new FileInputStream (path);
BM = Bitmapfactory.decodestream (IS, null, options);
catch (Exception e) {LOG.W (TAG, "Createbitmapbyscale Exception.", e);
catch (OutOfMemoryError e) {LOG.W (TAG, "Createbitmapbyscale outofmemoryerror.", e);
Todo:out of memory deal.
return BM; }
The above is to solve the Android reading picture size display problem, the need for friends can refer to the next.