很多时候,如果APP需要下载和加载很多图片(尤其是大图片)的时候,就往往会报如下图所示的错误:

如上图所示,OOM(OutOfMemoryError)表示内存溢出,这是因为网络或内存中的图片被加载成Bitmap时耗费的内存超出了系统内存而造成内存溢出。解决这个问题有很多方法,这里主要介绍其中的一种方法:图片压缩。

这里贴出一个工具类:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory; /**
* 图片压缩工具类
*/
public class ImageUtil {
/**
* 从指定路径获取Bitmap图片
*
* @param imgPath 原始图片的路径
*/
public static Bitmap getBitmap(String imgPath) {
// Get bitmap through image path
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = false;
newOpts.inPurgeable = true;
newOpts.inInputShareable = true;
// Do not compress
newOpts.inSampleSize = 1;
newOpts.inPreferredConfig = Config.RGB_565;
return BitmapFactory.decodeFile(imgPath, newOpts);
} /**
* 将图片存储到指定路径的文件中
*
* @param bitmap 原始图片Bitmap
* @param outPath 目标图片路径
*/
public static void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
FileOutputStream os = new FileOutputStream(outPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
} /**
* 尺寸压缩(改变图片的宽高),适合用于加载缩略图
*
* @param imgPath 图片路径
* @param pixelW 想要将图片压缩到的宽度
* @param pixelH 想要将图片压缩到的高度
*/
public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 开始读入图片,此时把options.inJustDecodeBounds 设回true,即只读边不读内容
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Config.RGB_565;
// Get bitmap info, but notice that bitmap is null now
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts); newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 想要缩放的目标尺寸
float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;//设置缩放比例
// 开始压缩图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
return bitmap;
} /**
* 尺寸压缩(改变图片的宽高),适合用于加载缩略图
*
* @param image 图片的Bitmap
* @param pixelW 想要将图片压缩到的宽度
* @param pixelH 想要将图片压缩到的高度
*/
public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
if (os.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
os.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%,把压缩后的数据存放到baos中
}
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
is = new ByteArrayInputStream(os.toByteArray());
bitmap = BitmapFactory.decodeStream(is, null, newOpts);
return bitmap;
} /**
* 质量压缩,然后存储到指定路径
*
* @param image 原始图片Bitmap
* @param outPath 目标图片路径
* @param maxSize 图片将被压缩成这么多KB
*/
public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// scale
int options = 100;
// Store the bitmap into output stream(no compress)
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// Compress by loop
while (os.toByteArray().length / 1024 > maxSize) {
// Clean up os
os.reset();
// interval 10
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
}
// Generate compressed image file
FileOutputStream fos = new FileOutputStream(outPath);
fos.write(os.toByteArray());
fos.flush();
fos.close();
} /**
* 质量压缩并存储到指定路径
*
* @param imgPath 想要压缩的图片路径
* @param outPath 目标图片路径
* @param maxSize 图片将被压缩成这么多KB
* @param needsDelete 压缩后是否删除原始图片
*/
public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {
compressAndGenImage(getBitmap(imgPath), outPath, maxSize);
if (needsDelete) {
File file = new File(imgPath);
if (file.exists()) {
file.delete();
}
}
} /**
* 尺寸压缩后保存图片
*
* @param image 原始图片Bitmap
* @param outPath 目标图片路径
* @param pixelW 想要将图片压缩到的宽度
* @param pixelH 想要将图片压缩到的高度
*/
public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {
Bitmap bitmap = ratio(image, pixelW, pixelH);
storeImage(bitmap, outPath);
} /**
* 尺寸压缩后保存图片,并决定是否删除原始图片
*
* @param imgPath 想要压缩的图片路径
* @param outPath 目标图片路径
* @param pixelW 想要将图片压缩到的宽度
* @param pixelH 想要将图片压缩到的高度
* @param needsDelete 是否删除原始图片
*/
public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {
Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
storeImage(bitmap, outPath);
if (needsDelete) {
File file = new File(imgPath);
if (file.exists()) {
file.delete();
}
}
}
}

【Android - 进阶】之图片压缩的更多相关文章

  1. Android中的图片压缩

    1.android中计算图片占用堆内存的kB大小跟图片本身的kB大小无关,而是根据图片的尺寸来计算的. 比如一张 480*320大小的图片占用的堆内存大小为: 480*320*4/1024=600kB ...

  2. Android笔记(七十五) Android中的图片压缩

    这几天在做图记的时候遇第一次遇到了OOM,好激动~~ 追究原因,是因为在ListView中加载的图片太大造成的,因为我使用的都是手机相机直接拍摄的照片,图片都比较大,所以在加载的时候会出现内存溢出,那 ...

  3. Android学习之图片压缩,压缩程度高且失真度小

    曾经在做手机上传图片的时候.直接获取相机拍摄的原图上传,原图大小一般1~2M.因此上传一张都比較浪费资源,有些场景还须要图片多张上传,所以近期查看了好多前辈写的关于图片处理的资料.然后试着改了一个图片 ...

  4. Android 简单介绍图片压缩和图片内存缓存

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/9316683 本篇文章主要内容来自于Android Doc,我翻译之后又做了些加工, ...

  5. 【Android 进阶】图片载入框架之Glide

    简单介绍 在泰国举行的谷歌开发人员论坛上,谷歌为我们介绍了一个名叫 Glide 的图片载入库,作者是 bumptech.这个库被广泛的运用在 google 的开源项目中,包含 2014 年 googl ...

  6. Android 中图片压缩分析(上)

    作者: shawnzhao,QQ音乐技术团队一员 一.前言 在 Android 中进行图片压缩是非常常见的开发场景,主要的压缩方法有两种:其一是质量压缩,其二是下采样压缩. 前者是在不改变图片尺寸的情 ...

  7. 每个人都要学的图片压缩终极奥义,有效解决 Android 程序 OOM

    # 由来 在我们编写 Android 程序的时候,几乎永远逃避不了图片压缩的难题.除了应用图标之外,我们所要显示的图片基本上只有两个来源: 来自网络下载 本地相册中加载 不管是网上下载下来的也好,还是 ...

  8. Android 图片压缩、照片选择、裁剪,上传、一整套图片解决方案

    1.Android一整套图片解决方案 http://mp.weixin.qq.com/s?__biz=MzAxMTI4MTkwNQ==&mid=2650820998&idx=1& ...

  9. Android图片压缩方法总结

    本文总结Android应用开发中三种常见的图片压缩方法,分别是:质量压缩法.比例压缩法(根据路径获取图片并压缩)和比例压缩法(根据Bitmap图片压缩).   第一:质量压缩方法:   ? 1 2 3 ...

随机推荐

  1. 【python之旅】python的模块

    一.定义模块: 模块:用来从逻辑上组织python代码(变量.函数.类.逻辑:实现一个功能),本质就是以.py结尾的python文件(文件名:test.py ,对应的模块名就是test) 包:用来从逻 ...

  2. Hive 的 排序

    全排序:order by对全部所有的数据进行排序,在实现的时候是放到一个reduce中进行的,可以想象这样做效率是比较低的: 局部排序:sort by对数据进行分组,然后在组内进行排序,每个reduc ...

  3. SecurityCRT输出日志重定向

    使用CRT进行抓取log,因为工具本省缓冲区有限,导致,刷屏特别快,可能会错过一些log,可以对CRT的log进行增加输出源,或者说将输出到控制台的log再输出到本地文件中: 文件->点击(勾选 ...

  4. mp4下载完后才能播放的问题

    下载完后才能播放的问题.mp4视频有metadata,通常在文件尾部,而flash读到这个metadata才开始播放,解决办法是用工具处理一下mp4,把它的metadata移至文件头部. 推荐工具:m ...

  5. Hadoop 学习笔记 (十) MapReduce实现排序 全局变量

    一些疑问:1 全排序的话,最后的应该sortJob.setNumReduceTasks(1);2 如果多个reduce task都去修改 一个静态的 IntWritable ,IntWritable会 ...

  6. 关于__irq 的使用

    __irq为一个标识,用来表示一个函数是否为中断函数. 对于不同的编译器,__irq在函数名中的位置不一样,例如: ADS编译器中 : void __irq IRQ_Eint0(void); Keil ...

  7. 利用merge优化

    create table a1(TP_END_DATE NUMBER,WK_END_DATE NUMBER, MTH_START_DATE NUMBER, MTH_END_DATE NUMBER, T ...

  8. WebSorcket学习

    传统 Web 模式在处理高并发及实时性需求的时候经常采用以下方案: 1.轮询,原理简单易懂,就是客户端通过一定的时间间隔以频繁请求的方式向服务器发送请求,来保持客户端和服务器端的数据同步.问题很明显, ...

  9. 嵌入式系统烧写uboot/bootloader/kernel的一般方法

    嵌入式系统烧写uboot/bootloader/kernel的一般方法   本文介绍了在嵌入式系统中烧写uboot/bootloader/kernel 的一般方法,以及如果uboot或者内核出现错误, ...

  10. C#编程技术层次

    不谈具体领域(比如搜索,视频,网络等),单就编程语言这个垂直方向,大体上对它有一个如下的层次划分. 1. 基本运用C#语法,在各种工具和示例代码的支持下,完成一些基本程序任务 2. 熟练掌握面向对象与 ...