JAVA中使用BufferedImage操作合成图片,在一张图片上加入新的图片和文字等等。其中Mat是opencv的类,懒得改了,本人试过使用OPENCV进行类似的处理,结果总是失败,所以把Mat转换成为BufferedImage后,再进行处理,以下是关键方法,供大家学习使用,省得走弯路,有使用Mat能够实现的同学也请指导一番。谢谢。
public static void drawNew(String filename,String filename2,String savepath) throws IOException{ Mat image = Highgui.imread(filename); Mat image2 = Highgui.imread(filename2); BufferedImage buf = Mat2BufferedImage(image); BufferedImage buf2 = Mat2BufferedImage(image2); // int w = image.width(),w1 = 200,h = image.height(); BufferedImage newimage = new BufferedImage(w + w1, h, BufferedImage.TYPE_INT_RGB); // Graphics2D g = newimage.createGraphics(); // draw start g.drawImage(buf, 0, 0, w, h, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1f)); g.drawImage(buf2, w, 0, w1, h, null); // 图片中标识 start g.setColor(Color.BLACK); g.drawString("目标数量:12", w + 1, 12); g.setColor(Color.RED); g.drawLine(w, 20, w + w1, 20); // end // list start g.setColor(Color.BLACK); for(int i = 0;i < 5;i++){ g.drawString("目标"+i+":10,20,100,100", w + 1, 30 + i * 15); } // draw end g.dispose(); ImageIO.write(newimage, "JPEG", new File(savepath)); }
public static Mat bufferedImage2Mat(BufferedImage in) { BufferedImage image = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // Draw the image onto the new buffer Graphics2D g = image.createGraphics(); try { g.setComposite(AlphaComposite.Src); g.drawImage(in, 0, 0, null); } finally { g.dispose(); } byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()) .getData(); Mat mat = Mat.eye(image.getHeight(), image.getWidth(), CvType.CV_8UC3); mat.put(0, 0, pixels); return mat; } public static BufferedImage Mat2BufferedImage(Mat image){ BufferedImage buf = null; MatOfByte mob = new MatOfByte(); Highgui.imencode(".jpg", image, mob); byte[] byteArray = mob.toArray(); InputStream in = new ByteArrayInputStream(byteArray); try { buf = ImageIO.read(in); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return buf; }