原本已经在度娘上搜出了各种压缩图片的处理方式,有暴力的失真的也有温柔的。
但是今天由于需求问题需要将图片压缩。
接下里就是压缩的代码
InputStream inputStream =null;
Bitmap bitmap =null;
try{
inputStream = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options options =newBitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeStream(inputStream, null,options);
// int imageHeight = options.outHeight;
// int imageWidth = options.outWidth;
options.inJustDecodeBounds=false;
options.inSampleSize= GlobalTool.computeSampleSize(options,-1,
512*512);
bitmap = BitmapFactory.decodeStream(inputStream, null,options);
}catch(FileNotFoundException e) {
//TODO Auto-generated catch block
}
以下就是压缩的计算代码
获取inSampleSize : intcomputeSampleSize
public static intcomputeSampleSize(BitmapFactory.Options options,
intminSideLength, intmaxNumOfPixels) {
intinitialSize =computeInitialSampleSize(options,minSideLength,
maxNumOfPixels);
introundedSize;
if(initialSize <=8) {
roundedSize=1;
while(roundedSize< initialSize) {
roundedSize<<=1;
}
}else{
roundedSize= (initialSize +7) /8*8;
}
return roundedSize;
}
获取intinitialSize
private static intcomputeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, intmaxNumOfPixels) {
doublew = options.outWidth;
doubleh = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ?1:
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ?128:
(int) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if(upperBound < lowerBound) {
return lowerBound;
}
if((maxNumOfPixels == -1) &&
(minSideLength == -1)) {
return1;
}else if(minSideLength == -1) {
return lowerBound;
}else{
return upperBound;
}
}
outW=2448.0/outH=3264.0
outW*outH=7990272.0
outW*outH/maxNumOfPixels=30.48046875
initialSize=6
roundedSize=8
scaleSize=1/8
byte=499392/rowCount=1224
height=408/width=306
上面还有一些打印的计算结果便于理解