123
This commit is contained in:
1 parent
1957b0a1ed
commit
f084d04808
5 files changed
+89
-1
No files matched your search
@@ -0,0 +1,61 @@
|
||||
package com.ruoyi.common.utils;
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Created by yihui on 2017/7/17.
|
||||
*/
|
||||
public class Base64Util {
|
||||
|
||||
public static String encode(BufferedImage bufferedImage, String imgType) throws IOException {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ImageIO.write(bufferedImage, imgType, outputStream);
|
||||
return encode(outputStream);
|
||||
}
|
||||
|
||||
public static String imageToBase64(String imagePath) {
|
||||
try {
|
||||
byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
|
||||
return Base64.getEncoder().encodeToString(imageBytes);
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
public static String encode(ByteArrayOutputStream outputStream) {
|
||||
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* base64转图片并保存到本地
|
||||
*
|
||||
* @param base64 base64字符串
|
||||
* @param imagePath 保存路径,例如 D:/test/output.png
|
||||
*/
|
||||
public static void base64ToImage(String base64, String imagePath) {
|
||||
// 去掉 data:image/png;base64, 这种前缀
|
||||
try {
|
||||
if (base64.contains(",")) {
|
||||
base64 = base64.substring(base64.indexOf(",") + 1);
|
||||
}
|
||||
byte[] imageBytes = Base64.getDecoder().decode(base64);
|
||||
try (FileOutputStream fos = new FileOutputStream(imagePath)) {
|
||||
fos.write(imageBytes);
|
||||
}
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
public static BufferedImage decode2Img(String base64) throws IOException {
|
||||
byte[] bytes = Base64.getDecoder().decode(base64.getBytes("utf-8"));
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
|
||||
return ImageIO.read(inputStream);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user