在Android开发中为了防止内存溢出,在显示图片时通常都对图片进行不同的压缩,以下就是压缩的代码:
第一步:先通过对图片大小及手机屏幕尺寸的计算得出来的值然后对图片的尺寸进行缩小,在这时尺寸压缩后,
在产生Bitmap时就不会出现OutOfMemoryException异常了。尺寸压缩使用Options的inSampleSize属性
来控制缩放比例。
第二步:压缩图片质量,根据文件大小来判断压缩程度。
- public Bitmap createNewBitmapAndCompressByFile(String filePath, int wh[]) {
- int offset = 100;
- File file = new File(filePath);
- long fileSize = file.length();
- if (200 * 1024 < fileSize && fileSize <= 1024 * 1024)
- offset = 90;
- else if (1024 * 1024 < fileSize)
- offset = 85;
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true; // 为true里只读图片的信息,如果长宽,返回的bitmap为null
- options.inPreferredConfig = Bitmap.Config.ARGB_8888;
- options.inDither = false;
- /**
- * 计算图片尺寸 //TODO 按比例缩放尺寸
- */
- BitmapFactory.decodeFile(filePath, options);
- int bmpheight = options.outHeight;
- int bmpWidth = options.outWidth;
- int inSampleSize = bmpheight / wh[1] > bmpWidth / wh[0] ? bmpheight / wh[1] : bmpWidth / wh[0];
- // if(bmpheight / wh[1] < bmpWidth / wh[0]) inSampleSize = inSampleSize * 2 / 3;//TODO 如果图片太宽而高度太小,则压缩比例太大。所以乘以2/3
- if (inSampleSize > 1)
- options.inSampleSize = inSampleSize;// 设置缩放比例
- options.inJustDecodeBounds = false;
- InputStream is = null;
- try {
- is = new FileInputStream(file);
- } catch (FileNotFoundException e) {
- return null;
- }
- Bitmap bitmap = null;
- try {
- bitmap = BitmapFactory.decodeStream(is, null, options);
- } catch (OutOfMemoryError e) {
- System.gc();
- bitmap = null;
- }
- if (offset == 100)
- return bitmap;// 缩小质量
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bitmap.compress(Bitmap.CompressFormat.JPEG, offset, baos);
- byte[] buffer = baos.toByteArray();
- options = null;
- if (buffer.length >= fileSize)
- return bitmap;
- return BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
- }