版权声明:https://blog.youkuaiyun.com/qq_32425789/article/details/85052201
直接上图
原图信息:
压缩后:
贴代码:压缩图片工具类 ! ! 第一个参数获取拿到的图片资源getResources()即可
, 第二个属性资源id, 第三四个 是打算将图片宽高 压到多大!
public class imageviewtool {
private static final String TAG = "MainActivity";
public static Bitmap decodeSampledBitmapResesouce(Resources res,int resId,int reqWidth,int reqHeight){
final BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeResource(res,resId,options);
options.inSampleSize=ImageSize(options,reqWidth,reqHeight);
options.inJustDecodeBounds=false;
return BitmapFactory.decodeResource(res,resId,options);
}
public static int ImageSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
final int height=options.outHeight;
final int width=options.outWidth;
int inSampleSize=1;
if(height>reqHeight ||width>reqWidth){
final int hanflHeight=height/2;
final int hanflWidth=width/2;
while (hanflHeight/inSampleSize>=reqHeight&&hanflWidth/inSampleSize>=reqWidth){
inSampleSize*=2;
}
}
return inSampleSize;
}
}
BitmapFactory.Options详解:https://www.cnblogs.com/nimorl/p/8065071.html
1.创建一个bitmap工厂类
final BitmapFactory.Options options=new BitmapFactory.Options();
2.如果将这个值置为true,那么在解码的时候将不会返回bitmap,只会返回这个bitmap的尺寸。这个属性的目的是,如果你只想知道一个bitmap的尺寸,但又不想将其加载到内存时。这是一个非常有用的属性。
options.inJustDecodeBounds=true;
3.获取资源,1.Resource资源,2.图片id,3.最后一个参数就为Options 高效处理图片属性
BitmapFactory.decodeResource(res,resId,options);
坑来了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Bitmap mBt = BitmapFactory.decodeResource(getResources(), R.mipmap.yasuo);
mBt.getWidth()
mBt.getHeight()
日志打出 宽:2240 高:1400
BitmapFactory.Options options=new BitmapFactory.Options();
options.outHeight;
options.outWidth;
日志打出 宽:2560 高:1600
what??????! (手动黑人问号) 查看原图,options 拿到的才是真正的宽高, emmmmmmmm
O(∩_∩)O哈哈~
这个我也不知道, 查了貌似是图片编码问题 ....... 求留言指点呀...
4. inSampleSize这个值是一个int,当它小于1的时候,将会被当做1处理,如果大于1,那么就会按照比例(1 / inSampleSize)缩小bitmap的宽和高、降低分辨率,大于1时这个值将会被处置为2的倍数。例如,width=100,height=100,inSampleSize=2,那么就会将bitmap处理为,width=50,height=50,宽高降为1 / 2,像素数降为1 / 4。
options.inSampleSize=ImageSize(options,reqWidth,reqHeight);
第一个参数原图属性,在potions中,第二第三个参数压缩到宽高为多少 我上面写的10所以......
5.最后将压缩完成的图片以bitmap返回出去 ..