java在图片上绘制框框

/**
     * 画缺陷框的图片文件
     * @param file {@link File}
     * @param polygon 缺陷框
     * @return 带缺陷的文件
     * @throws IOException IO异常
     */
    public static File drawLine(File file, String polygon) throws IOException {
        // 图片路径
        InputStream in = new FileInputStream(file);
        BufferedImage image = ImageIO.read(file);
        Graphics g = image.getGraphics();
        // 只有强制转换成这个类型才可以设置画笔粗细
        Graphics2D g2 = (Graphics2D) g;
        // 画笔粗细
        g2.setStroke(new BasicStroke(5.0f));
        g2.setColor(Color.RED);


        DefectBoxVo drewObject = JSON.parseObject(polygon, DefectBoxVo.class);
        g2.drawRect(drewObject.getX(), drewObject.getY(), drewObject.getW(), drewObject.getH());
        // 输出图片的地址
        FileOutputStream out = new FileOutputStream(file);
        ImageIO.write(image, "jpg", out);
        out.close();
        in.close();
        return file;
    }

参数解释参照Graphics类drawRect()方法参数详解

posted @ 2022-10-09 09:09  xiexie0812  阅读(244)  评论(0编辑  收藏  举报