1.需求
有一个原始图片,并提供了x坐标、y坐标、宽度、高度,实现在原图片上进行框选标注画图
2.目标效果
原图:
框选标注后:
3.代码实现
简介:只需要使用java自带的扩展包(rt.jar)方法即可实现
3.1核心方法
/**
*
* @param originalPicture 原始图片地址
* @param x:该参数用于返回检测框左上角位置的横坐标(x)所在的像素位置,结合剩余参数可唯一确定检测框的大小和位置。
* @param y:该参数用于返回检测框左上角位置的纵坐标(y)所在的像素位置,结合剩余参数可唯一确定检测框的大小和位置。
* @param width: 该参数用于返回检测框的宽度(由左上角出发在x轴向右延伸的长度),结合剩余参数可唯一确定检测框的大小和位置。
* @param height:该参数用于返回检测框的高度(由左上角出发在y轴向下延伸的长度),结合剩余参数可唯一确定检测框的大小和位置。
* @param drawColor:画框的颜色
* @return
* @throws Exception
*/
private static void drawAndGetPictureUrl(String originalPicture, int x, int y, int width, int height, Color drawColor) {
BufferedImage bufferedImage = null;
//读取图片文件,得到BufferedImage对象
try {
if (StringUtils.isEmpty(originalPicture)) {
log.error("绘制图片失败:原始图片地址为空");
return;
}
InputStream inputStream = null;
HttpURLConnection connection = (HttpURLConnection) new URL(originalPicture).openConnection();
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
}
bufferedImage = ImageIO.read(inputStream);
//得到Graphics2D 对象
Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
//设置颜色、画笔粗细
g2D.setColor(drawColor);
g2D.setStroke(new BasicStroke(5));
//绘制矩形
g2D.drawRect(x, y, width, height);
g2D.setFont(new Font("", Font.BOLD, 40));
//绘制文字
g2D.drawString("XXX洗衣液", x+10, y+60);
ByteArrayOutputStream os = new ByteArrayOutputStream();
String savePath = "/Users/pingtaiyanfa-lihongjie/tmp/test.jpg";
ImageIO.write(bufferedImage, CommonUtil.getImgFormat(originalPicture), new FileOutputStream(savePath));
} catch (Exception e) {
log.error("绘制图片失败:,原图片:{},error:{}", originalPicture, e);
}
}
3.2测试
public static void main(String[] args) throws Exception {
int width = 283;
int height = 355;
int y = 20;//top
int x = 149;//left
String originalPicture = "http://xxx.jpg";
drawAndGetPictureUrl(originalPicture, x, y, width, height, Color.RED);
}