给客户做了两张报表,导出两张图片,但是客户非要导出到一张图片,然后就用java把两张图片合成一张了。
package com.zws;import java.awt.Graphics;import java.awt.p_w_picpath.BufferedImage;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.p_w_picpathio.ImageIO;public class ImageConcat { public static void main(String[] args) throws IOException { String img0 = "G:/0.png"; String img1 = "G:/1.png"; String savePath = "G:/concat1.png"; concat(img0, img1, savePath, "png", 0); //concat(img0, img1, savePath, null, 1); } /** * * @param img0 图片一路径 * @param img1 图片二路径 * @param savePath 图片保存路径 * @param formateName 合成图片格式 * @param conType 合成类型,0:左右拼接,1:上下拼接 * @throws IOException */ public static void concat(String img0, String img1, String savePath, String formateName, int conType) throws IOException { InputStream in0 = new FileInputStream(img0); InputStream in1 = new FileInputStream(img1); byte[] byts = concat(in0, in1, formateName, conType); FileOutputStream out = new FileOutputStream(savePath); out.write(byts); out.close(); } /** * * @param byts0 图片一 * @param byts1 图片二 * @param savePath 图片保存路径 * @param formateName 合成图片格式 * @param conType 合成类型,0:左右拼接,1:上下拼接 * @throws IOException */ public static void concat(byte[] byts0, byte[] byts1, String savePath, String formateName, int conType) throws IOException { InputStream in0 = new ByteArrayInputStream(byts0); InputStream in1 = new ByteArrayInputStream(byts1); byte[] byts = concat(in0, in1, formateName, conType); FileOutputStream out = new FileOutputStream(savePath); out.write(byts); out.close(); } /** * * @param in0 图片一 * @param in1 图片二 * @param formateName 合成图片格式 * @param conType 合成类型,0:左右拼接,1:上下拼接 * @throws IOException */ public static byte[] concat(InputStream in0, InputStream in1, String formateName, int conType) throws IOException { BufferedImage bi0 = ImageIO.read(in0); BufferedImage bi1 = ImageIO.read(in1); int width = 0, height = 0; if (conType == 0) { //左右拼接 width = bi0.getWidth() + bi1.getWidth(); height = bi0.getHeight() >= bi1.getHeight() ? bi0.getHeight() : bi1.getHeight(); } else { //上下拼接 width = bi0.getWidth() >= bi1.getWidth() ? bi0.getWidth() : bi1.getWidth(); height = bi0.getHeight() + bi1.getHeight(); } BufferedImage conc = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); int x0 = 0, y0 = 0, widthX0 = bi0.getWidth(), heightY0 = bi0.getHeight(); int x1 = 0, y1 = 0, widthX1 = bi1.getWidth(), heightY1 = bi1.getHeight(); if (conType == 0) { x1 = bi0.getWidth(); y1 = 0; } else { x1 = 0; y1 = bi0.getHeight(); } Graphics graphics = conc.createGraphics(); graphics.drawImage(bi0, x0, y0, widthX0, heightY0, null); graphics.drawImage(bi1, x1, y1, widthX1, heightY1, null); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(conc, formateName, output); output.close(); in0.close(); in1.close(); return output.toByteArray(); }}
如果两张图片尺寸相同的话合成是比较完美的,但是如果尺寸不同就会有空白。