package com.*.util;

 import java.io.FileInputStream;

 import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date; import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder; public class Base64ImgUtils {
public static void main(String[] args) {
String strImg = GetImageStr();
System.out.println(strImg);
GenerateImage(strImg);
} /**
* 图片转化成base64字符串
* GetImageStr
* 2016年8月31日下午3:37:40
* @param
* @return
*/
public static String GetImageStr() {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
String imgFile = "D:/486e407765c21edd9cbffca69717efb1.jpg";// 待处理的图片
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
String imghead="data:image/jpg;base64,";//头
return imghead+encoder.encode(data);// 返回Base64编码过的字节数组字符串
} /**
* base64字符串转化成图片
* GenerateImage
* 2016年8月31日下午3:33:12
* @param
* @return
*/
public static String GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null){ // 图像数据为空
return "";
}
String classPath = new Base64ImgUtils().getClass().getResource("").getPath();
String path = classPath.substring(, classPath.indexOf("WEB-INF"));
System.out.println(path);
BASE64Decoder decoder = new BASE64Decoder();
try {
String imghead=imgStr.substring(,imgStr.indexOf(";")).replace("data:image/", ".");//获取图片扩展名
imgStr=imgStr.substring(imgStr.indexOf(",")+);//图片内容 // Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = ; i < b.length; ++i) {
if (b[i] < ) {// 调整异常数据
b[i] += ;
}
}
// 生成jpeg图片
String filename="upload/"+new Date().getTime()+imghead;//名称
String imgFilePath =path+"/"+filename;// 新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return filename;
} catch (Exception e) {
return "";
}
} }

最新文章

  1. java EE设计模式简介
  2. webView和js交互
  3. 【URAL 1917】Titan Ruins: Deadly Accuracy(DP)
  4. C++:异常的处理
  5. mac 功能修改。。。。
  6. twemproxy 简介
  7. ssis的script task作业失败(调用外部dll)
  8. hack:选择符前缀法,样式属性前缀法
  9. bootstrap 鼠标悬停显示
  10. Python3使用PyQt5制作简单的画板/手写板
  11. 《C语言点滴》书评
  12. python正常时间和unix时间戳时间的相互转换源码
  13. ubuntu16.04 caffe 安装
  14. Codeforces.1129E.Legendary Tree(交互 二分)
  15. CentOS6.8下Jenkins+maven+tomcat+git+shell自动构建、部署web应用环境的搭建
  16. ribbbitMq 教程,详细
  17. 从django的序列化到rest-framework 序列化
  18. python---基础知识回顾(二)(闭包函数和装饰器)
  19. 使用 Python 在 Linux 上实现一键回归测试
  20. Ubuntu16.04 / OpenCV / Python 源码安装

热门文章

  1. Factors and Multiples
  2. mui初级入门教程(二)— html5+ webview 底部栏用法详解
  3. php面试专题---16、MySQL创建高性能索引考点
  4. innobackupex对MySQL做热备份,报错mysql库下数据字典表损坏
  5. scrapy--meta参数传递问题
  6. WebService-.Net:添加web引用和添加服务引用有什么区别?
  7. 使用 Vagrant 搭建 Kubernetes 本地测试环境
  8. UCenter 与 DIscuz 通信失败的解决方法
  9. memcpy不能复制内存重叠区域,memmove可以拷贝重叠内存
  10. 高德WMTS规则