原创

base64字符串解码转换成图片

温馨提示:
本文最后更新于 2016年11月19日,已超过 2,714 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我
	/** 
     * 1.base64字符串转化成图片(对字节数组字符串进行Base64解码并生成图片)  
     * 2.首先要检查是否存在data:image/png;base64,(类似content-type),如果有的话, 去掉。 
     * 3.通过BASE64Decoder 接口进行解码 (BASE64Decoder位于%JAVA_HOME%\jdk1.7.0_45\jre\lib\rt.jar中)  
     * 4.最后通过FileOutputStream 文件流生成文件 
     *  
     * @param base64Str  
     * @param filePath 
     * @author zhangyd-c 
     * @return String 
     */  
    public static String generateImage(String base64Str, 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;  
                }  
            }  
            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;  
    }  


正文到此结束
本文目录