java 图片画框并读取成base64数据

  • Post author:
  • Post category:java


示例的rectangle坐标数据形式为”1,10;1,110;101,10;101,110″,供参考

//需要引入的包贴一下
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

画框方法:鉴于我的参数格式是四个点,我选择的是划线方法drawLine,参数格式比较方便的其实可以使用drawRect方法,我的具体写法如下,仅供参考,其中画完以后也可以处理成图片,鉴于我的业务需求我这边是转成了base64供后面用

  private String drawRect(String imageUrl, String rectangle) throws Exception {
        // new一个URL对象
        URL url = new URL(imageUrl);
        BufferedImage image = ImageIO.read(url);
        Graphics g = image.getGraphics();
        g.setColor(Color.RED);//画笔颜色
        if (!StringUtils.isEmpty(rectangle)) {
            String[] points = rectangle.split(";");
            if (points.length > 3) {
                String[] pointOne = points[0].split(",");
                String[] pointTwo = points[1].split(",");
                String[] pointThree = points[2].split(",");
                String[] pointFour = points[3].split(",");
                g.drawLine(Integer.valueOf(pointOne[0]), Integer.valueOf(pointOne[1]), Integer.valueOf(pointTwo[0]), Integer.valueOf(pointTwo[1]));
                g.drawLine(Integer.valueOf(pointOne[0]), Integer.valueOf(pointOne[1]), Integer.valueOf(pointThree[0]), Integer.valueOf(pointThree[1]));
                g.drawLine(Integer.valueOf(pointTwo[0]), Integer.valueOf(pointTwo[1]), Integer.valueOf(pointFour[0]), Integer.valueOf(pointFour[1]));
                g.drawLine(Integer.valueOf(pointThree[0]), Integer.valueOf(pointThree[1]), Integer.valueOf(pointFour[0]), Integer.valueOf(pointFour[1]));
                //图片转base64
                ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
                ImageIO.write(image,"jpg",outputStream);
                byte[] bytes=outputStream.toByteArray();
                BASE64Encoder encode = new BASE64Encoder();
                String base64String = encode.encode(bytes);
                if (!StringUtils.isEmpty(base64String)) {
                    System.out.println("顺利生成框测图的base64数据" + base64String.substring(0, 20));
                }
                outputStream.close();
                g.dispose();
                return base64String;
            }
        }
        return "";
    }



版权声明:本文为liumeixiang777原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。