图片压缩保存

来源:互联网 发布:mysql解压包怎么安装 编辑:程序博客网 时间:2024/05/31 19:34
         
         因为图片存储特性,当前内存读取Byte构造的Bitmap如不存储则只能使用一次。因为图片大小缩放是图片自生属性操作。图片质量变化,属于动态像素模糊。所以图片质量缩放对应的内存输出流不能保留。则在存储压缩图片的时候,需要再次进行质量压缩。

第一:我们先看一下文件命名:

 

    private static char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6',            '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};    private static String toHexString(byte[] b) {        StringBuilder sb = new StringBuilder(b.length * 2);        for (int i = 0; i < b.length; i++) {            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);            sb.append(HEX_DIGITS[b[i] & 0x0f]);        }        return sb.toString();    }

第二:我们来压缩保存图片:
 /** 保存图片到本地路径 */    public String saveFile(Bitmap image, int limitKB) {        try {            ByteArrayOutputStream baos = new ByteArrayOutputStream();            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);            int options = 100;            while (baos.size() / 1024 > limitKB) {                baos.reset();                image.compress(Bitmap.CompressFormat.JPEG, options, baos);                options -= 10;            }            byte[] tempBytes = baos.toByteArray();            MessageDigest md5 = MessageDigest.getInstance("MD5");                   // md5图片获得md5码            md5.update(tempBytes);            String imageMd5 = toHexString(md5.digest()).toLowerCase();            ByteArrayOutputStream arrayOutputStream = null;            String imageRoot = FilePathUtils.getUserEditPath();            String filename = imageRoot + imageMd5 + ".jpg";            FileOutputStream outputStream = new FileOutputStream(new File(filename));            arrayOutputStream = new ByteArrayOutputStream();            arrayOutputStream.write(tempBytes);            arrayOutputStream.writeTo(outputStream);            return filename;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

0 0
原创粉丝点击