Java实现图片拼接

时间:2022-12-06 16:07:04

本文实例为大家分享了java实现图片拼接的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
 * 拼接图片(注:图片需长宽一致)
 * @param files  img1 ,img2
 * @param type  1:横向拼接 2:纵向拼接
 * @param targetfile 合成新的图片地址
 */
public static void mergeimage(string[] files, int type, string targetfile) {
 int len = files.length;
 if (len < 1) {
  throw new runtimeexception("图片数量小于1");
 }
 file[] src = new file[len];
 bufferedimage[] images = new bufferedimage[len];
 int[][] imagearrays = new int[len][];
 for (int i = 0; i < len; i++) {
  try {
   src[i] = new file(files[i]);
   images[i] = imageio.read(src[i]);
  } catch (exception e) {
   throw new runtimeexception(e);
  }
  int width = images[i].getwidth();
  int height = images[i].getheight();
  imagearrays[i] = new int[width * height];
  imagearrays[i] = images[i].getrgb(0, 0, width, height, imagearrays[i], 0, width);
 }
 int newheight = 0;
 int newwidth = 0;
 for (int i = 0; i < images.length; i++) {
  // 横向
  if (type == 1) {
   newheight = newheight > images[i].getheight() ? newheight : images[i].getheight();
   newwidth += images[i].getwidth();
  } else if (type == 2) {// 纵向
   newwidth = newwidth > images[i].getwidth() ? newwidth : images[i].getwidth();
   newheight += images[i].getheight();
  }
 }
 if (type == 1 && newwidth < 1) {
  return;
 }
 if (type == 2 && newheight < 1) {
  return;
 }
 // 生成新图片
 try {
  bufferedimage imagenew = new bufferedimage(newwidth, newheight, bufferedimage.type_int_rgb);
  int height_i = 0;
  int width_i = 0;
  for (int i = 0; i < images.length; i++) {
   if (type == 1) {
    imagenew.setrgb(width_i, 0, images[i].getwidth(), newheight, imagearrays[i], 0,
      images[i].getwidth());
    width_i += images[i].getwidth();
   } else if (type == 2) {
    imagenew.setrgb(0, height_i, newwidth, images[i].getheight(), imagearrays[i], 0, newwidth);
    height_i += images[i].getheight();
   }
  }
  //输出想要的图片
  imageio.write(imagenew, targetfile.split("\\.")[1], new file(targetfile));
 } catch (exception e) {
  throw new runtimeexception(e);
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_38114563/article/details/81408417