现在的位置: 首页 > 综合 > 正文

压缩图片

2013年08月29日 ⁄ 综合 ⁄ 共 984字 ⁄ 字号 评论关闭
public static Bitmap resizeBitMapImage1(String filePath, int targetWidth, 
            int targetHeight) { 
        Bitmap bitMapImage = null; 
        // First, get the dimensions of the image 
        Options options = new Options(); 
        options.inJustDecodeBounds = true; 
        BitmapFactory.decodeFile(filePath, options); 
        double sampleSize = 0; 
        // Only scale if we need to 
        // (16384 buffer for img processing) 
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math 
                .abs(options.outWidth - targetWidth); 
 
        if (options.outHeight * options.outWidth * 2 >= 1638) { 
            // Load, scaling to smallest power of 2 that'll get it <= desired 
            // dimensions 
            sampleSize = scaleByHeight ? options.outHeight / targetHeight 
                    : options.outWidth / targetWidth; 
            sampleSize = (int) Math.pow(2d, 
                    Math.floor(Math.log(sampleSize) / Math.log(2d))); 
        } 
 
        // Do the actual decoding 
        options.inJustDecodeBounds = false; 
        options.inTempStorage = new byte[128]; 
        while (true) { 
            try { 
                options.inSampleSize = (int) sampleSize; 
                bitMapImage = BitmapFactory.decodeFile(filePath, options); 
 
                break; 
            } catch (Exception ex) { 
                try { 
                    sampleSize = sampleSize * 2; 
                } catch (Exception ex1) { 
 
                } 
            } 
        } 
 
        return bitMapImage; 
    } 

抱歉!评论已关闭.