public static Bitmap readBitmapAutoSize(String filePath, int outWidth, int outHeight) {
FileInputStream fs =
null
;
BufferedInputStream bs =
null
;
try
{
fs =
new
FileInputStream(filePath);
bs =
new
BufferedInputStream(fs);
BitmapFactory.Options ptions = setBitmapOption(filePath, outWidth, outHeight);
return
BitmapFactory.decodeStream(bs,
null
, options);
}
catch
(Exception e) {
e.printStackTrace();
} finally {
try
{
bs.close();
fs.close();
}
catch
(Exception e) {
e.printStackTrace();
}
}
return
null
;
}
private static BitmapFactory.Options setBitmapOption(String file, int width, int height) {
BitmapFactory.Options pt =
new
BitmapFactory.Options();
opt.inJustDecodeBounds =
true
;
BitmapFactory.decodeFile(file, opt);
int utWidth = opt.outWidth;
int utHeight = opt.outHeight;
opt.inDither =
false
;
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inSampleSize = 1;
if
(outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
int sampleSize = (outWidth / width + outHeight / height) / 2;
opt.inSampleSize = sampleSize;
}
opt.inJustDecodeBounds =
false
;
return
opt;
}
另外,decodeStream直接拿的图片来读取字节码了, 不会根据机器的各种分辨率来自动适应, 使用了decodeStream之后,需要在hdpi和mdpi,ldpi中配置相应的图片资源, 否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。
可参考下面的代码:
java代码:
BitmapFactory.Options pts = new BitmapFactory.Options();
opts.inTargetDensity = ctx.getResources().getDisplayMetrics().densityDpi;
opts.inScaled = true ;
最后要注意,图片的bitmap对象一般为大对象,不用了要注意主动回收:
if (!bmp.isRecycle() ){
bmp.recycle()
system.gc()
}
|
|