import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
public class ImageUtil {
/**
* 图片转Base64码
* @param src
* @return
*/
public static String convertImageToBase64Str(String src) {
ByteArrayOutputStream baos = null;
try {
String suffix = src.substring(src.lastIndexOf(".") + 1);
File imageFile = new File(src);
BufferedImage bufferedImage = ImageIO.read(imageFile);
baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, suffix, baos);
byte[] bytes = baos.toByteArray();
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Base64码转图片
* @param base64String
* @param newSrc
*/
public static void convertBase64StrToImage(String base64String, String newSrc) {
ByteArrayInputStream bais = null;
try {
String suffix = newSrc.substring(newSrc.lastIndexOf(".") + 1);
byte[] bytes = Base64.getDecoder().decode(base64String);
bais = new ByteArrayInputStream(bytes);
BufferedImage bufferedImage = ImageIO.read(bais);
File imageFile = new File(newSrc);
ImageIO.write(bufferedImage, suffix, imageFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bais != null) {
bais.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java实现图片和base64之间的互转
最新推荐文章于 2025-03-02 00:15:00 发布