当前位置:操作系统 > 安卓/Android >>

android图片压缩

[java]
/**
 * 从文件解析出Bitmap格式的图片
 * 
 * @param path
 * @param maxWidth
 * @param maxHeight
 * @return
 */ 
public static Bitmap decodeFile(String path, int maxWidth, int maxHeight){ 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    Bitmap image = null; 
    image = BitmapFactory.decodeFile(path, options); 
    double ratio = 1D; 
    if (maxWidth > 0 && maxHeight <= 0) { 
        // 限定宽度,高度不做限制  
        ratio = Math.ceil(options.outWidth / maxWidth); 
    } else if (maxHeight > 0 && maxWidth <= 0) { 
        // 限定高度,不限制宽度  
        ratio = Math.ceil(options.outHeight / maxHeight); 
    } else if (maxWidth > 0 && maxHeight > 0) { 
        // 高度和宽度都做了限制,这时候我们计算在这个限制内能容纳的最大的图片尺寸,不会使图片变形  
        double _widthRatio = Math.ceil(options.outWidth / maxWidth); 
        double _heightRatio = (double) Math.ceil(options.outHeight / maxHeight); 
        ratio = _widthRatio > _heightRatio ? _widthRatio : _heightRatio; 
    } 
    if (ratio > 1) { 
        options.inSampleSize = (int) ratio; 
    } 
    options.inSampleSize = calcScaleRatio(maxWidth, maxHeight, options.outWidth, options.outHeight); 
    options.inJustDecodeBounds = false; 
    options.inPreferredConfig = Bitmap.Config.RGB_565; 
    image = BitmapFactory.decodeFile(path, options); 
    return image; 

    /**
     * 从文件解析出Bitmap格式的图片
     *
     * @param path
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    public static Bitmap decodeFile(String path, int maxWidth, int maxHeight){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap image = null;
        image = BitmapFactory.decodeFile(path, options);
        double ratio = 1D;
        if (maxWidth > 0 && maxHeight <= 0) {
            // 限定宽度,高度不做限制
            ratio = Math.ceil(options.outWidth / maxWidth);
        } else if (maxHeight > 0 && maxWidth <= 0) {
            // 限定高度,不限制宽度
            ratio = Math.ceil(options.outHeight / maxHeight);
        } else if (maxWidth > 0 && maxHeight > 0) {
            // 高度和宽度都做了限制,这时候我们计算在这个限制内能容纳的最大的图片尺寸,不会使图片变形
            double _widthRatio = Math.ceil(options.outWidth / maxWidth);
            double _heightRatio = (double) Math.ceil(options.outHeight / maxHeight);
            ratio = _widthRatio > _heightRatio ? _widthRatio : _heightRatio;
        }
        if (ratio > 1) {  www.zzzyk.com
            options.inSampleSize = (int) ratio;
        }
        options.inSampleSize = calcScaleRatio(maxWidth, maxHeight, options.outWidth, options.outHeight);
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        image = BitmapFactory.decodeFile(path, options);
        return image;
    }


作者:liao3841054
补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,