package gui.picture;




import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import util.io.FilesAndFolders;

public class ImageMergeKRISI extends JFrame {

	private BufferedImage finalImg;
	BufferedImage temp;
	public ImageMergeKRISI() {
		super("ImageMerge2");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

	public static void main(String[] args) throws IOException {
		new ImageMergeKRISI().processImages();
	}

	/**
	 *
	 */
	private void processImages() throws IOException {
		int rows = 4;   
		int cols = 3;  
		int chunks = rows * cols;  

		int sliceWidth, sliceHeight;  
		int type;  
		//fetching image files  
		//            File[] imgFiles = new File[chunks];  
		//            for (int i = 0; i < chunks; ) {  
		//                imgFiles[i] = new File("c:/imgs/oben.jpg");  
		//                i++; // zum testen
		//                imgFiles[i] = new File("c:/imgs/unten.jpg");
		//                i++;
		//            }  

		File folder = new File("./testdaten/big/");  
		ArrayList<File> imgFiles = FilesAndFolders.listPicturesRec(folder);


		//creating a bufferd image array from image files  
		BufferedImage[] buffImages = new BufferedImage[chunks];  
		for (int i = 0; i < chunks; i++) {  
			buffImages[i] = ImageIO.read(imgFiles.get(i%imgFiles.size()));  
		}  
		type = buffImages[0].getType();  
		sliceWidth = buffImages[0].getWidth();  
		sliceHeight = buffImages[0].getHeight();  

		//Initializing the final image  
		finalImg = new BufferedImage(sliceWidth*cols, sliceHeight*rows, type);  

		int num = 0;  
		for (int i = 0; i < rows; i++) {  
			for (int j = 0; j < cols; j++) {  
				finalImg.createGraphics().drawImage(buffImages[num], sliceWidth * j, sliceHeight * i, null);  
				num++;  
			}  
		}  

		ImageIO.write(finalImg, "jpg", new File("finalImg.jpg"));  
		System.out.println("Fertig....File gespeichert"); 

		// temp = new BufferedImage(1024, 768, finalImg.getType());
		// Image temp2  = finalImg.getScaledInstance(1024, 800, Image.SCALE_FAST);
		finalImg.getGraphics().drawImage(finalImg, 0, 0, this);
		setSize(finalImg.getWidth(), finalImg.getHeight());

	}



	@Override
	public void paint(Graphics g) {
		if (finalImg != null) {
			g.drawImage(finalImg, 0, 0, this);
		}
	}
}