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.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;

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;
    }
}

ImageCompress.java

调用方式:

Object srcPath; // 源图片,可以是sdcard文件路径,也可以是图片库的Uri
String dstPath; // 压缩后的保存路径
CompressOptions options = new CompressOptions();
options.destFile = new File(dstPath);
options.maxWidth = 1000;
options.maxHeight = 1280;
options.uri = (srcPath instanceof Uri) ? ((Uri)srcPath) : Uri.fromFile(new File(srcPath.toString()));

Bitmap bitMap = new ImageCompress().compressFromUri(context, options);

Android图片压缩的更多相关文章

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

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

  2. android图片压缩方法

    android 图片压缩方法: 第一:质量压缩法: private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = ...

  3. android图片压缩的3种方法实例

    android 图片压缩方法: 第一:质量压缩法: private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = ...

  4. Android 图片压缩器

    概述 Android 图片压缩器:一款高效的图片压缩器库,支持批量压缩,异步压缩.多线程多任务压缩,压缩比设置等特性. 详细 代码下载:http://www.demodashi.com/demo/12 ...

  5. Android 图片压缩各种方式

       前言:由于公司项目当中需要用到压缩这块的相应技术,之前也做过的图片压缩都不是特别的理想, 所以这次花了很多心思,仔细研究和在网上找到了很多相对应的资料.为了就是 以后再做的时候直接拿来用就可以了 ...

  6. Android图片压缩上传(二)

    之前有用到libjpeg,还是有一定的局限性,最近用了一个新的方式,效果还是挺不错,随着作者的版本更新,Bug也随之变少,目前项目中运用已上线. 1.之前的方式Android图片压缩,不失真,上线项目 ...

  7. Android图片压缩方法总结

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

  8. 性能优化——Android图片压缩与优化的几种方式

    图片优化压缩方式大概可以分为以下几类:更换图片格式,质量压缩,采样率压缩,缩放压缩,调用jpeg压缩等1.设置图片格式Android目前常用的图片格式有png,jpeg和webp,png:无损压缩图片 ...

  9. android图片压缩总结

    一.bitmap 图片格式介绍 android中图片是以bitmap形式存在的,那么bitmap所占内存,直接影响到了应用所占内存大小,首先要知道bitmap所占内存大小计算方式: bitmap内存大 ...

随机推荐

  1. 【NOIP 2015 DAY2 T3】 运输计划 (树链剖分-LCA)

    题目背景 公元 2044 年,人类进入了宇宙纪元. 题目描述 L 国有 n 个星球,还有 n-1 条双向航道,每条航道建立在两个星球之间,这 n-1 条航道连通了 L 国的所有星球. 小 P 掌管一家 ...

  2. easyui表单提交,后台获取不到值

    J2ee开发,使用easyui表单提交,在ie中可以正常将参数传递到后台,但使用firefox,chrome都无法将easyui的combobox值传递到后台,使用alert($('#form').s ...

  3. WCF - Architecture

    WCF - Architecture WCF has a layered architecture that offers ample support for developing various d ...

  4. Android开发之注解式框架ButterKnife在ADT中的设置

    使用注解式框架ButterKnife的时候,导入到ADT中,结果项目中注解的view无效,如点击button等无任何的反应. 然后在ButterKnife的官网查看到解决办法:http://jakew ...

  5. Chrome的隐身模式

    先来说说隐身模式的启用方法吧 1.键盘快捷:Ctrl + Shift + N. 2.在Windows7下的任务栏处,右击“Chrome”图标,会出一个下拉菜单,点击“新建隐身窗口”. 3.你还可以在一 ...

  6. android手机屏幕分辨率 及 sp dip(dp) px 区别 及高中低分辨率时处理

    分辨率,是指单位长度内包含的像素点的数量,它的单位通常为像素/英寸(ppi).以分辨率为1024×768的屏幕来说,即每一条水平线上包含有1024个像素点,共有768条线,即扫描列数为1024列,行数 ...

  7. [转]ASP.NET MVC 入门6、TempData

    ASP.NET MVC的TempData用于传输一些临时的数据,例如在各个控制器Action间传递临时的数据或者给View传递一些临时的数据,相信大家都看过“在ASP.NET页面间传值的方法有哪几种” ...

  8. 纯CSS的颜色渐变效果

    本例展示了一个纯css渐变的效果.其兼容IE6以上浏览器等各主流浏览器: 案例效果:查看演示 代码如下: css: *{margin:0;padding:0;} .linear{ width:100% ...

  9. Java笔记(十三)……面向对象III继承(inheritance)

    继承概述 继承概述 多个类中存在相同属性和行为时,将这些内容抽取到单独一个类中,那么多个类无需再定义这些属性和行为,只要继那个类即可. 多个类可以称为子类,单独这个类称为父类或者超类. 子类可以直接访 ...

  10. NOIP2015 子串 (DP+优化)

    子串 (substring.cpp/c/pas) [问题描述] 有两个仅包含小写英文字母的字符串 A 和 B.现在要从字符串 A 中取出 k 个 互不重 叠 的非空子串,然后把这 k 个子串按照其在字 ...