Utils.java如下:
package cn.loadImages;
import java.io.InputStream;
import java.io.OutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class Utils {
public static void copyStream(InputStream is, OutputStream os){
final int buffer_size=1024;
try{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1){
break;
}
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
//获取图片的缩略图
public static Bitmap getBitmapThumbnail(String filePath,int minSideLength, int maxNumOfPixels ){
BitmapFactory.Options options=new BitmapFactory.Options();
//true那么将不返回实际的bitmap对象
//不给其分配内存空间但是可以得到一些解码边界信息即图片大小等信息
options.inJustDecodeBounds=true;
//此时rawBitmap为null
Bitmap rawBitmap = BitmapFactory.decodeFile(filePath, options);
if (rawBitmap==null) {
System.out.println("此时rawBitmap为null");
}
//inSampleSize表示缩略图大小为原始图片大小的几分之一,若该值为3
//则取出的缩略图的宽和高都是原始图片的1/3,图片大小就为原始大小的1/9
//计算sampleSize
int sampleSize=computeSampleSize(options, minSideLength, maxNumOfPixels);
//为了读到图片,必须把options.inJustDecodeBounds设回false
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize;
//原图大小为625x690 90.2kB
//测试调用computeSampleSize(options, 100, 200*100);
//得到sampleSize=8
//得到宽和高位79和87
//79*8=632 87*8=696
Bitmap thumbnailBitmap=BitmapFactory.decodeFile(filePath, options);
return thumbnailBitmap;
}
//参考资料:
//http://my.csdn.net/zljk000/code/detail/18212
//第一个参数:原本Bitmap的options
//第二个参数:希望生成的缩略图的宽高中的较小的值
//第三个参数:希望生成的缩量图的总像素
public static int computeSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {
//原始图片的宽
double w = options.outWidth;
//原始图片的高
double h = 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 the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
}