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的更多相关文章

  1. Android --------- 压缩图片的尺寸和大小

    压缩图片大小,尺寸不变 将已知路径的图片压缩至不大于目标大小,并保存至指定路径 /** * 质量压缩,通过给定的路径来压缩图片并保存到指定路径 * * @param srcPath * 资源图片的路径 ...

  2. 关于Android中图片大小、内存占用与drawable文件夹关系的研究与分析

    原文:关于Android中图片大小.内存占用与drawable文件夹关系的研究与分析 相关: Android drawable微技巧,你所不知道的drawable的那些细节 经常会有朋友问我这个问题: ...

  3. Android压缩图片到100K以下并保持不失真的高效方法

    前言:目前一般手机的相机都能达到800万像素,像我的Galaxy Nexus才500万像素,拍摄的照片也有1.5M左右.这么大的照片上传到服务器,不仅浪费流量,同时还浪费时间. 在开发Android企 ...

  4. java 上传图片 并压缩图片大小

    Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...

  5. java 上传图片 并压缩图片大小(转)

    Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...

  6. 【问题帖】压缩图片大小至指定Kb以下

    像PS,QQ影像等都有该功能,将图片大小压缩至指定kb以下. 我也来山寨一把,到目前为止,控制图片的大小,平时的解决方案通过分辨率和质量来控制的. 假定最后压缩的大小是100kb,那么在保证不大于10 ...

  7. java上传图片并压缩图片大小

    Thumbnailator 是一个优秀的图片处理的Google开源Java类库.处理效果远比Java API的好.从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生 ...

  8. java实现上传图片并压缩图片大小功能

    缩略图压缩文件jar包 <!-- 图片缩略图 --> <dependency> <groupId>net.coobird</groupId> <a ...

  9. 压缩图片大小(Java源码)

    /** * * 直接指定压缩后的宽高: * @param oldFile * 要进行压缩的文件 * @param width * 压缩后的宽度 * @param height * 压缩后的高度 * @ ...

随机推荐

  1. 这份Mybatis总结,我觉得你很需要!

    前言 只有光头才能变强. 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y Mybatis应该是国内用得最多的「数据访问层」 ...

  2. 数据源管理 | PostgreSQL环境整合,JSON类型应用

    本文源码:GitHub·点这里 || GitEE·点这里 一.PostgreSQL简介 1.和MySQL的比较 PostgreSQL是一个功能强大的且开源关系型数据库系统,在网上PostgreSQL和 ...

  3. ES6中不得不说的关键字const

    上一节讲了let关键字,它是用来声明一个变量,只在块级作用域起作用.这一节我们来学习ES6新增的另一个关键字const. const 的作用 const是constant(常量)的缩写,const和 ...

  4. Apk优化极致

    1. webp WebP格式,谷歌(google)开发的一种旨在加快图片加载速度的图片格式.图片压缩体积大约只有JPEG的2/3,并能节省大量的服务器宽带资源和数据空间.Facebook Ebay等知 ...

  5. 使用cat命令清空文件

    比如要清空 /www/aaa.txt cat /dev/null > /www/aaa.txt; 即可.

  6. 梁国辉获Yes评分表系统3.0计算机软件著作权

    梁国辉获Yes评分表系统3.0计算机软件著作权 Liang Guohui won the Yes score system 3 computer software copyright 登记证书如下 R ...

  7. 备忘录模式 (c++实现)

    模式定义 备忘录(Memento): 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态.这样以后就可以将该对象恢复到原先保存的状态. 模式动机 备忘录模式比较适用于功能比较复 ...

  8. 【Linux常见命令】diff命令

    diff - compare files line by line diff命令用于比较文件的差异. diff以逐行的方式,比较文本文件的异同处. 如果指定要比较目录,则diff会比较目录中相同文件名 ...

  9. 打造livecd的注意事项

    一:在CentOS.ks的定制脚本中,删除syslinux组件:出错提示: /usr/lib/python2.6/site-packages/imgcreate/errors.py:45: Depre ...

  10. Makefile中的CFLAGS,LDFLAGS,LIBS

    CFLAGS:C编译器选项,而CXXFLAGS表示C++编译器的选项 1. CFLAGS参数 选项 说明 -c 用于把源码编译成.o对象文件,不进行链接过程 -o 用于连接生成可执行文件,在其后可以指 ...