首页 > android 如何把Bitmap进行压缩?

android 如何把Bitmap进行压缩?

现在在做微信的图片分享,之前一直测试失败,后来得知缩略图的大小要在32K以下(不想吐槽腾讯的文档),请问如何把Bitmap进行压缩?


简单粗暴上代码

 /**
     * 图片质量压缩
     * @param image
     * @param srcPath 要保存的路径
     * @return
     */
    public static Bitmap compressImage(Bitmap image, String srcPath) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {    // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中

        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        try {
            FileOutputStream out = new FileOutputStream(srcPath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

解码时使用insamplesesize进行大小调节
使用Bitmap compress压缩时将quality设的低一些


分享是友盟的吗

如果是就用友盟的就好了

 mUMImage = new UMImage(context, shareImageUrl);
 weiXinShare.setShareImage(mUMImage);
【热门文章】
【热门文章】