// 获取图片的缩略图,宽度和高度中较小的缩放到vMinWidth. 确保宽度和高度最小的都能覆盖到,
//比如图片是3000*2000,要缩放到 150*100, 那么vMinWidth=100;
//如果图片比预期最小宽度小,就不用缩放了
public static Bitmap getThumbImgAtMinWidth(String vPath, int vMinWidth) {
Log.v("getThumbImgAtMinWidth", "1==");
if(null == vPath){
Log.v("getThumbImgAtMinWidth", "路径为null");
return null;
}
if(vPath.trim().equals("")){
Log.v("getThumbImgAtMinWidth", "路径为空");
return null;
}
Log.v("getThumbImgAtMinWidth", "path="+vPath+", 期望:vMinWidth="+vMinWidth);
File file = new File(vPath);
//如果不存在了,直接返回
if(!file.exists()){
Log.v("getThumbImgAtMinWidth", "文件不存在:path="+vPath);
return null;
}
// 先获取图片的宽和高
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(vPath, options);
if (options.outWidth <= 0 || options.outHeight <= 0) {
Log.v("getThumbImgAtMinWidth", "解析图片失败");
return null;
}
Log.v("getThumbImgAtMinWidth", "原图大小:width:" + options.outWidth + ",height:"
+ options.outHeight + ",path=" + vPath);
int height0 = options.outHeight;
int tMinWidth = Math.min(options.outWidth, options.outHeight);
// 压缩图片,注意inSampleSize只能是2的整数次幂,如果不是的,话,向下取最近的2的整数次幂,例如3实际上会是2,7实际上会是4
options.inSampleSize = Math.max(1, tMinWidth/vMinWidth);
//Log.v("getThumbImgAtMinWidth", "options.inSampleSize="+options.inSampleSize);
options.inPreferredConfig = Config.RGB_565;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inJustDecodeBounds = false;
Bitmap thumbImgNow = null;
try{
thumbImgNow = BitmapFactory.decodeFile(vPath, options);
}catch(OutOfMemoryError e){
Log.v("getThumbImgAtMinWidth", "OutOfMemoryError, decodeFile失败 ");
return null;
}
//Log.v("getThumbImgAtMinWidth", "thumbImgNow.size="+thumbImgNow.getWidth()+","+thumbImgNow.getHeight());
if(null == thumbImgNow){
Log.v("getThumbImgAtMinWidth", "decodeFile失败 ");
return null;
}
int wid = thumbImgNow.getWidth();
int hgt = thumbImgNow.getHeight();
//Log.v("getThumbImgAtMinWidth", "after scale, 1, tEndWidth="+wid+",tEndHeight="+hgt);
int degree = readPictureDegree(vPath);
if (degree != 0) {
//Log.v("getThumbImgAtMinWidth", "degree="+degree);
// 把图片旋转为正的方向
thumbImgNow = rotateImage(degree, thumbImgNow);
}
wid = thumbImgNow.getWidth();
hgt = thumbImgNow.getHeight();
tMinWidth = Math.min(wid, hgt);
if (tMinWidth > vMinWidth) {
//如果原图片最小宽度比预期最小高度大才进行缩小
float ratio = ((float) vMinWidth) / tMinWidth;
Matrix matrix = new Matrix();
matrix.postScale(ratio, ratio);
thumbImgNow = Bitmap.createBitmap(thumbImgNow, 0, 0, wid, hgt, matrix, true);
}
Log.v("getThumbImgAtMinWidth", "处理后, size, width="+thumbImgNow.getWidth()+",height="+thumbImgNow.getHeight());
return thumbImgNow;
}
android取缩略图
最新推荐文章于 2021-06-03 04:32:49 发布