android 压缩图片大小,防止OOM
android开发中,图片的处理是非常普遍的,经常是需要将用户选择的图片上传到服务器,但是现在手机的分辨率越来越好了,随便一张照片都是2M或以上,如果直接显示到ImageView中,是会出现OOM的,上传到如服务器也会占用大量的流量,用户体验肯定不好了!
下面自己实现了图片的显示以及压缩功能,主要代码是从Volley的ImageRequest中copy过来,作为工具类方便以后图片处理
package com.img.util; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream; import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.Log; /**
* 图片压缩工具类
*
* @author Administrator
*
*/
public class ImageCompress { public static final String CONTENT = "content";
public static final String FILE = "file"; /**
* 图片压缩参数
*
* @author Administrator
*
*/
public static class CompressOptions {
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 800; public int maxWidth = DEFAULT_WIDTH;
public int maxHeight = DEFAULT_HEIGHT;
/**
* 压缩后图片保存的文件
*/
public File destFile;
/**
* 图片压缩格式,默认为jpg格式
*/
public CompressFormat imgFormat = CompressFormat.JPEG; /**
* 图片压缩比例 默认为30
*/
public int quality = 30; public Uri uri;
} public Bitmap compressFromUri(Context context,
CompressOptions compressOptions) { // uri指向的文件路径
String filePath = getFilePath(context, compressOptions.uri); if (null == filePath) {
return null;
} BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; Bitmap temp = BitmapFactory.decodeFile(filePath, options); int actualWidth = options.outWidth;
int actualHeight = options.outHeight; int desiredWidth = getResizedDimension(compressOptions.maxWidth,
compressOptions.maxHeight, actualWidth, actualHeight);
int desiredHeight = getResizedDimension(compressOptions.maxHeight,
compressOptions.maxWidth, actualHeight, actualWidth); options.inJustDecodeBounds = false;
options.inSampleSize = findBestSampleSize(actualWidth, actualHeight,
desiredWidth, desiredHeight); Bitmap bitmap = null; Bitmap destBitmap = BitmapFactory.decodeFile(filePath, options); // If necessary, scale down to the maximal acceptable size.
if (destBitmap.getWidth() > desiredWidth
|| destBitmap.getHeight() > desiredHeight) {
bitmap = Bitmap.createScaledBitmap(destBitmap, desiredWidth,
desiredHeight, true);
destBitmap.recycle();
} else {
bitmap = destBitmap;
} // compress file if need
if (null != compressOptions.destFile) {
compressFile(compressOptions, bitmap);
} return bitmap;
} /**
* compress file from bitmap with compressOptions
*
* @param compressOptions
* @param bitmap
*/
private void compressFile(CompressOptions compressOptions, Bitmap bitmap) {
OutputStream stream = null;
try {
stream = new FileOutputStream(compressOptions.destFile);
} catch (FileNotFoundException e) {
Log.e("ImageCompress", e.getMessage());
} bitmap.compress(compressOptions.imgFormat, compressOptions.quality,
stream);
} private static int findBestSampleSize(int actualWidth, int actualHeight,
int desiredWidth, int desiredHeight) {
double wr = (double) actualWidth / desiredWidth;
double hr = (double) actualHeight / desiredHeight;
double ratio = Math.min(wr, hr);
float n = 1.0f;
while ((n * 2) <= ratio) {
n *= 2;
} return (int) n;
} private static int getResizedDimension(int maxPrimary, int maxSecondary,
int actualPrimary, int actualSecondary) {
// If no dominant value at all, just return the actual.
if (maxPrimary == 0 && maxSecondary == 0) {
return actualPrimary;
} // If primary is unspecified, scale primary to match secondary's scaling
// ratio.
if (maxPrimary == 0) {
double ratio = (double) maxSecondary / (double) actualSecondary;
return (int) (actualPrimary * ratio);
} if (maxSecondary == 0) {
return maxPrimary;
} double ratio = (double) actualSecondary / (double) actualPrimary;
int resized = maxPrimary;
if (resized * ratio > maxSecondary) {
resized = (int) (maxSecondary / ratio);
}
return resized;
} /**
* 获取文件的路径
*
* @param scheme
* @return
*/
private String getFilePath(Context context, Uri uri) { String filePath = null; if (CONTENT.equalsIgnoreCase(uri.getScheme())) { Cursor cursor = context.getContentResolver().query(uri,
new String[] { Images.Media.DATA }, null, null, null); if (null == cursor) {
return null;
} try {
if (cursor.moveToNext()) {
filePath = cursor.getString(cursor
.getColumnIndex(Images.Media.DATA));
}
} finally {
cursor.close();
}
} // 从文件中选择
if (FILE.equalsIgnoreCase(uri.getScheme())) {
filePath = uri.getPath();
} return filePath;
}
}
使用方式:
<span style="white-space:pre"> </span>ImageCompress compress = new ImageCompress();
ImageCompress.CompressOptions options = new ImageCompress.CompressOptions();
options.uri = imgUri;
options.maxWidth=getWindowManager().getDefaultDisplay().getWidth();
options.maxHeight=getWindowManager().getDefaultDisplay().getHeight();
Bitmap bitmap = compress.compressFromUri(this, options);
默认压缩比例为30%,可以根据实际情况修改。
android 压缩图片大小,防止OOM的更多相关文章
- Android --------- 压缩图片的尺寸和大小
压缩图片大小,尺寸不变 将已知路径的图片压缩至不大于目标大小,并保存至指定路径 /** * 质量压缩,通过给定的路径来压缩图片并保存到指定路径 * * @param srcPath * 资源图片的路径 ...
- 关于Android中图片大小、内存占用与drawable文件夹关系的研究与分析
原文:关于Android中图片大小.内存占用与drawable文件夹关系的研究与分析 相关: Android drawable微技巧,你所不知道的drawable的那些细节 经常会有朋友问我这个问题: ...
- Android压缩图片到100K以下并保持不失真的高效方法
前言:目前一般手机的相机都能达到800万像素,像我的Galaxy Nexus才500万像素,拍摄的照片也有1.5M左右.这么大的照片上传到服务器,不仅浪费流量,同时还浪费时间. 在开发Android企 ...
- java 上传图片 并压缩图片大小
Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
- java 上传图片 并压缩图片大小(转)
Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
- 【问题帖】压缩图片大小至指定Kb以下
像PS,QQ影像等都有该功能,将图片大小压缩至指定kb以下. 我也来山寨一把,到目前为止,控制图片的大小,平时的解决方案通过分辨率和质量来控制的. 假定最后压缩的大小是100kb,那么在保证不大于10 ...
- java上传图片并压缩图片大小
Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...
- java实现上传图片并压缩图片大小功能
缩略图压缩文件jar包 <!-- 图片缩略图 --> <dependency> <groupId>net.coobird</groupId> <a ...
- 压缩图片大小(Java源码)
/** * * 直接指定压缩后的宽高: * @param oldFile * 要进行压缩的文件 * @param width * 压缩后的宽度 * @param height * 压缩后的高度 * @ ...
随机推荐
- [Yii2] 快速套模板,加载JS,CSS(HTML标签<base>)
刚开始学,弄了好久,不知道怎么加载JS.CSS,以及怎么不加载YII2自带的模板!其实真的好简单! 补: 其实是我垃圾,YII2默认访问路径是WEB,所以把style文件放到web下就能加载! 首先把 ...
- 【考试总结】欢乐模拟赛_Day1
\(T1\) 题目描述 给出一个 \(n × n\) 的, 元素为自然数的矩阵. 这个矩阵有许许多多个子矩阵, 定义它的所有子矩阵形成的集合为 \(S\) . 对于一个矩阵 \(k\) , 定义 \( ...
- C# 静态变量、静态函数、实体变量、实体函数在一个类中的执行顺序
为了弄清这个代码,写了个测试,但是测试的结果和往上的代码有所差别,仁者见仁,智者见智了.如果我的测试用例用问题,欢迎指出. 首先,方法的是在被调用时执行,但是静态方法在所有地方都可以调用,应该在很早的 ...
- 【Spring源码分析】预备篇
前言 最新想学习一下Spring源码,开篇博客记录下学习过程,欢迎一块交流学习. 作为预备篇,主要演示搭建一个最简单的Spring项目样例,对Spring进行最基本梳理. 构建一个最简单的spring ...
- SpringCloud-Bus 消息总线
概述 基本介绍 Spring Cloud Bus 目前支持两种消息代理:RabbitMQ.Kafka Spring Cloud Config 配合 Spring Cloud Bus 使用可以实现配置的 ...
- 从源码解读Spring如何解决bean循环依赖
1 什么是bean的循环依赖 循环依赖的原文是circular reference,指多个对象相互引用,形成一个闭环. 以两个对象的循环依赖为例: Spring中的循环依赖有 3 种情况: 构造器(c ...
- Python数据分析:大众点评数据进行选址
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:砂糖侠 如果你处于想学Python或者正在学习Python,Pyth ...
- GithubAction-Deploy
GithubAction-Deploy githubhexoaction 使用 github action 自动化部署 创建GitHub repository 存放源文件 在repo设置界面里添加Se ...
- Excel中的clean函数
纯属note. 之前经常用excel处理数据的时候,对长文本或网站上拉取的值都会用clean函数清除一些我们肉眼看不到的非打印字符. Excel官方介绍:clean 删除文本中的所有非打印字符. 此次 ...
- python实现二分叉查找
*二分叉查找就是折半查找 比如12345这几个数字当中找2,他会先找到这五个数字中的中坚的那个与2进行比较,比如中间的3>2他就认为3以后的不用查找了,然后查找3左边的,即123,再把这个分半, ...