jar 包是 commons-codec.jar.
- pnuts
- //base64 解码成图片
- function gldBase64ToImage(imgStr,imgFilePath) {
- // 对字节数组字符串进行 Base64 解码并生成图片
- if ("".equals(imgStr) || imgStr == null) // 图像数据为空
- return false
- // 转码的时候它可能有前缀格式, 所以需要拆分, 取有效字符串
- imgArr = imgStr.split(",")
- if(imgArr.length == 1){
- imgStr = imgArr[0]
- }else{
- imgStr = imgArr[1]
- }
- imgByte = class org.apache.commons.codec.binary.Base64::decodeBase64(imgStr)
- // Base64 解码
- for (i = 0; i < imgByte.length; ++i) {
- if (imgByte[i] < 0) {// 调整异常数据
- imgByte[i] += 256;
- }
- }
- out = class java.io.FileOutputStream(imgFilePath)
- out.write(imgByte)
- out.flush()
- out.close()
- }
- java
- /**
- * 对字节数组字符串进行 Base64 解码并生成图片
- * @param imgStr 图片数据
- * @param imgFilePath 保存图片全路径地址
- * @return
- */
- public static boolean generateImage(String imgStr,String imgFilePath){
- //
- if ( "".equals(imgStr) || imgStr == null) // 图像数据为空
- return false;
- try
- {
- //Base64 解码
- byte[] b = Base64.decodeBase64(imgStr);
- for(int i=0;i<b.length;++i)
- {
- if(b[i]<0)
- {// 调整异常数据
- b[i]+=256;
- }
- }
- // 生成 jpeg 图片
- OutputStream out = new FileOutputStream(imgFilePath);
- out.write(b);
- out.flush();
- out.close();
- return true;
- }
- catch (Exception e)
- {
- return false;
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2801106.html