合并一组等大的图片文件成一个大图片
- import java.io.File;
- import java.io.IOException;
- import java.awt.image.BufferedImage;
- import javax.imageio.ImageIO;
- public class MergePics {
- public void mergeTwoFiles(String fn1, String fn2, String fnOut)
- throws IOException {
- File file1 = new File(fn1);
- BufferedImage image1 = ImageIO.read(file1);
- int width = image1.getWidth();
- int height = image1.getHeight();
- int[] imageArray1 = new int[width * height];
- imageArray1 = image1.getRGB(0, 0, width, height, imageArray1,
- 0, width);
- File file2 = new File(fn2);
- BufferedImage image2 = ImageIO.read(file2);
- int[] imageArray2 = new int[width * height];
- imageArray2 = image2.getRGB(0, 0, width, height, imageArray2,
- 0, width);
- BufferedImage imageNew = new BufferedImage(width * 2, height,
- BufferedImage.TYPE_INT_RGB);
- imageNew.setRGB(0, 0, width, height, imageArray1, 0, width);
- imageNew.setRGB(width, 0, width, height, imageArray2, 0, width);
- File outFile = new File(fnOut);
- ImageIO.write(imageNew, "png", outFile);
- }
- public boolean mergeFiles(String[] fns, int num, String fnOut)
- throws IOException {
- if (fns.length < num || num <= 0) {
- return false;
- }
- BufferedImage image = ImageIO.read(new File(fns[0]));
- int w = image.getWidth();
- int h = image.getHeight();
- int numH = (int)Math.ceil(fns.length / num);
- int numW = num;
- BufferedImage imageNew = new BufferedImage(numW * w, numH * h,
- BufferedImage.TYPE_INT_RGB);
- int[] imageArray = new int[w * h];
- imageArray = image.getRGB(0, 0, w, h, imageArray, 0, w);
- imageNew.setRGB(0, 0, w, h, imageArray, 0, w);
- for (int i = 0, nW = 0, nH = 0; i < fns.length; i++, nW++) {
- if (i == 0) continue;
- if (nW == num) {
- nW = 0;
- nH++;
- System.out.println("");
- }
- BufferedImage img = ImageIO.read(new File(fns[i]));
- imageArray = img.getRGB(0, 0, w, h, imageArray, 0, w);
- imageNew.setRGB(nW * w, nH * h, w, h, imageArray, 0, w);
- System.out.print("(" + nH + ", " + nW + ") ");
- }
- File outFile = new File(fnOut);
- ImageIO.write(imageNew, "png", outFile);
- return true;
- }
- public void testMergeTwoFiles() {
- String fn1 = "d:" + File.separator + "1" + File.separator +
- "g1.png";
- String fn2 = "d:" + File.separator + "1" + File.separator +
- "g2.png";
- String fnOut = "d:" + File.separator + "1" + File.separator + "2.png";
- try {
- this.mergeTwoFiles(fn1, fn2, fnOut);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void testMergeFiles() {
- String fnprefix = "d:" + File.separator + "1" + File.separator;
- String[] fns = new String[16];
- for (int j = 0; j < fns.length; j++) {
- fns[j] = fnprefix + "pic" + j + ".png";
- System.out.println(j);
- }
- String fnOut = fnprefix + "out.png";
- try {
- this.mergeFiles(fns, 4, fnOut);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- MergePics mp = new MergePics();
- mp.testMergeFiles();
- }
- }