工作日记第一篇(图片处理《压缩》)

原本已经在度娘上搜出了各种压缩图片的处理方式,有暴力的失真的也有温柔的。

但是今天由于需求问题需要将图片压缩。

接下里就是压缩的代码


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

上面还有一些打印的计算结果便于理解

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文始发于我的博文App图片压缩裁剪原理和上传方案,以及那些有趣的事儿...,现转发至此。 目录 App怎么压缩质...
    zackzheng阅读 19,790评论 20 130
  • 一直以来Bitmap都是开发中很棘手的问题,这个问题就是传说中的OOM(java.lang.OutofMemory...
    M悇芐冋忆阅读 10,325评论 0 11
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,627评论 25 709
  • 1.概述 在开发中,对于图片的操作,稍有不慎,可能就会消耗大量的内存,导致程序崩溃,所以了解一种通用的技术去处理和...
    GYLEE阅读 3,345评论 0 8
  • 我们知道,根据明代戏剧家汤显祖的《牡丹亭》改编的《还魂记》有很多剧种,包括昆剧、越剧、赣剧、黄梅戏等等。其中京剧梅...
    福二姨阅读 21,935评论 33 24