java项目开发难免会遇到不同的客户的需求,没错我们要不断的满足客户的需求。今天在项目遇到一个将两张图片纵向拼接起来成为一张图片。到网上找了很多方法都会报异常,因为两张图片大小不一样会溢出,经过我的修改不会出现任何问题了。具体代码如下:
/**
* 图片拼接
* 江风成
* @param files 要拼接的文件列表
* @param type2 纵向拼接
* @return
*/
public static InputStream merge(String[] files, int type) {
ByteArrayInputStream in=null;
try {
/* 1 读取第一张图片 */
File fileOne = new File(files[0]);
BufferedImage imageFirst = ImageIO.read(fileOne);
int width = imageFirst.getWidth();// 图片宽度
int height = imageFirst.getHeight();// 图片高度
int[] imageArrayFirst = new int[width * height];// 从图片中读取RGB
imageArrayFirst = imageFirst.getRGB(0, 0, width, height, imageArrayFirst, 0, width);
/* 1 对第二张图片做相同的处理 */
File fileTwo = new File(files[1]);
BufferedImage imageSecond = ImageIO.read(fileTwo);
int width1 = imageSecond.getWidth();// 图片宽度
int height2 = imageSecond.getHeight();// 图片高度
int[] imageArraySecond = new int[width1 * height2];
imageArraySecond = imageSecond.getRGB(0, 0, width1, height2, imageArraySecond, 0, width1);
int ww = width > width1 ? width : width1;
// 生成新图片
BufferedImage imageResult = new BufferedImage(ww, height2 + height, BufferedImage.TYPE_INT_RGB);
int k = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < ww; j++) {
if (width > j) {
imageResult.setRGB(j, i, imageArrayFirst[k]);
k++;
} else {
imageResult.setRGB(j, i, -328966);
}
}
}
int k1 = 0;
for (int i1 = 0; i1 < height2; i1++) {
for (int j1 = 0; j1 < ww; j1++) {
if (width1 > j1) {
imageResult.setRGB(j1, i1 + height, imageArraySecond[k1]);
k1++;
} else {
imageResult.setRGB(j1, i1 + height, -328966);
}}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(imageResult, “jpg”, out);// 写图片
in= new ByteArrayInputStream(out.toByteArray());
return in;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}