java图片生成图片base64
时间: 2023-08-21 08:02:19 浏览: 168
java将图片转为base64返回给前端
5星 · 资源好评率100%
你可以使用Java的`java.awt.Image`和`javax.imageio.ImageIO`类来生成图片,并将其转换为Base64编码。以下是一个示例代码:
```java
import java.awt.*;
import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.Base64;
public class ImageToBase64 {
public static void main(String[] args) {
try {
// 读取原始图片
File inputFile = new File("input.jpg");
BufferedImage originalImage = ImageIO.read(inputFile);
// 创建新的图片
BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = newImage.createGraphics();
graphics.drawImage(originalImage, 0, 0, null);
graphics.dispose();
// 将图片转换为Base64编码
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(newImage, "jpg", baos);
byte[] imageBytes = baos.toByteArray();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
System.out.println("Base64编码的图片:\n" + base64Image);
} catch (IOException e) {
阅读全文