/**
* 将二进制转换为图片
* @param base64String
*/
public static File base64StringToImage(String base64String){
try {
byte[] bytes1 = Base64Utils.decodeFromString(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 =ImageIO.read(bais);
File w2 = new File("e://aa/QQ.jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动
return w2;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
1.将流输出返回给前端
调用base64StringToImage(base64String),返回file文件到controller层处理,返回file是为了将图片临时存放在一个文件里面;处理完之后再将图片删除即可;
2.在controller处理
public void loadingImg(根据需求确定要不要参数) {
byte[] imageByte = null;
FileInputStream inputStream = null;
InputStream input = null;
BufferedInputStream bis = null;
OutputStream os = null;
BufferedOutputStream out = null;
File file = null;
try {
file = ;// 调用service的方法
inputStream = new FileInputStream(file);
input = new BufferedInputStream(inputStream);
bis = new BufferedInputStream(input);
os = response.getOutputStream();
out = new BufferedOutputStream(os);
byte[] buffer = new byte[2048]; // 创建存放输入流的缓冲
int num = -1; // 读入的字节数
while (true) {
num = bis.read(buffer); // 读入到缓冲区
if (num == -1) {
out.flush();
break; // 已经读完
}
out.flush();
out.write(buffer, 0, num);
}
} catch (Exception e) {
_log.error("loadingImg error", e);
} finally {
try {
if (null != out) {
out.close();
}
if (null != bis) {
bis.close();
}
if (null != input) {
input.close();
}
if (null != inputStream) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 删除图片,要注意必须在关流之后才能将图片删除,否则是无法删除的
file.delete();
}
3.将图片转换成二进制的方法
/**
* 将图片转换成二进制
* @return
*/
public static String getImageBinary(){
BASE64Encoder encoder = new BASE64Encoder();
File f = new File("e:/1.jpg");
BufferedImage bi;
try {
bi = ImageIO.read(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}