`
843977358
  • 浏览: 241622 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

base64字符串转换成图片

    博客分类:
  • java
阅读更多

    关于base64字符串转换成图片。

    前段时间在项目中用到了上传头像,并且获取剪切后的头像功能,单一的上传头像很好处理,直接把改文件上传就可以,但是剪切后的头像,它的src却是一个base64字符串,如图:

 ,直接将这个地址当做文件路径上传到后台肯定不行,因为java无法编译改地址,不能识别为一个图片路径。那么, 这就用到了对base64位字符串进行解码处理, 将其解析为一个可被正确识别的文件。

/**
     * <p>
     * 1.base64字符串转化成图片(对字节数组字符串进行Base64解码并生成图片)
     * </p>
     * <p>
     * 2.首先要检查是否存在data:image/png;base64,(类似content-type),如果有的话, 去掉。
     * </p>
     * <p>
     * 3.通过BASE64Decoder 接口进行解码 (BASE64Decoder位于%JAVA_HOME%\jdk1.7.0_45\jre\lib\rt.jar中)
     * </p>
     * <p>
     * 4.最后通过FileOutputStream 文件流生成文件
     * </p>
     * 
     * @param base64Str
     * @param userName
     * @param filePath
     * @author zhangyd-c
     * @date 2015年5月29日 下午2:49:22
     * @return String
     */
    public static String generateImage(String base64Str, String userName,String filePath) {
        // 去掉前面的data:image/png;base64,
        if (base64Str.indexOf("data:image/png;base64,") != -1) {
            base64Str = base64Str.replace("data:image/png;base64,", "");
        }
        BASE64Decoder decoder = new BASE64Decoder();
        // 生成jpeg图片
        FileOutputStream out = null;
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(base64Str);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            if (EmptyUtil.isNullStr(filePath)) {
                String newFileName = userName + CommonUtil.getDateString(new Date(), "yyyyMMhhHHmmss") + ".jpg";// 生成的新的文件名
                filePath = getFilePath() + newFileName;
            }
            out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            return null;
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return filePath;
    }
 

 

  • 大小: 294.1 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics