接口上传base64编码图片
2024-08-29 02:38:43
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 "";
}
} }
最新文章
- java EE设计模式简介
- webView和js交互
- 【URAL 1917】Titan Ruins: Deadly Accuracy(DP)
- C++:异常的处理
- mac 功能修改。。。。
- twemproxy 简介
- ssis的script task作业失败(调用外部dll)
- hack:选择符前缀法,样式属性前缀法
- bootstrap 鼠标悬停显示
- Python3使用PyQt5制作简单的画板/手写板
- 《C语言点滴》书评
- python正常时间和unix时间戳时间的相互转换源码
- ubuntu16.04 caffe 安装
- Codeforces.1129E.Legendary Tree(交互 二分)
- CentOS6.8下Jenkins+maven+tomcat+git+shell自动构建、部署web应用环境的搭建
- ribbbitMq 教程,详细
- 从django的序列化到rest-framework 序列化
- python---基础知识回顾(二)(闭包函数和装饰器)
- 使用 Python 在 Linux 上实现一键回归测试
- Ubuntu16.04 / OpenCV / Python 源码安装