package com.oracle;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class WriteImageDemo {
public static void main(String[] args) {
// 图片路径
String imagePath = "D:\\11.jpg"; // 替换为你的图片路径
// 加载图片
BufferedImage image = null;
try {
image = ImageIO.read(new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
}
if (image != null) {
// 获取图片宽度和高度
int width = image.getWidth();
int height = image.getHeight();
// 创建一个副本图像,在其上绘制框
BufferedImage resultImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resultImage.createGraphics();
// 在副本图像上绘制原始图像
g.drawImage(image, 0, 0, null);
// 设置框的颜色和宽度
g.setColor(Color.RED);
g.setStroke(new BasicStroke(2)); // 设置线宽
// 根据给定的 x 和 y 坐标绘制框
int x = 100; // 替换为你的 x 坐标
int y = 200; // 替换为你的 y 坐标
int boxWidth = 200; // 框的宽度
int boxHeight = 150; // 框的高度
g.drawRect(x, y, boxWidth, boxHeight);
g.dispose(); // 释放资源
// 将绘制了框的图像保存为新的文件
String outputImagePath = "D:\\image_with_box.jpg"; // 新图片保存路径
try {
ImageIO.write(resultImage, "jpg", new File(outputImagePath));
System.out.println("New image with bounding box saved to: " + outputImagePath);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Failed to load the image.");
}
}
}