package test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;

public class main {

	public static void main(String[] args) {
		BufferedImage image = null;

		try {
			// get the BufferedImage, using the ImageIO class
			image = ImageIO.read(new File("sanomali.png"));
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}

		int w = image.getWidth();
		int h = image.getHeight();
		System.out.println("width, height: " + w + ", " + h);

		// read pixels
		int[] array = new int[h * w];
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				System.out.println("x,y: " + j + ", " + i);
				int pixel = image.getRGB(j, i);
				array[i * 25 + j] = pixel;

				// just for information
				int red = (pixel >> 16) & 0xff;
				int green = (pixel >> 8) & 0xff;
				int blue = (pixel) & 0xff;
				System.out
						.println("R: " + red + " G: " + green + " B: " + blue);

			}
		}

		// sort
		Arrays.sort(array);

		// write pixels
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				System.out.println("x,y: " + j + ", " + i);
				int pixel = array[(i * 25 + j)];
				image.setRGB(j, i, pixel);

				// just for information
				int red = (pixel >> 16) & 0xff;
				int green = (pixel >> 8) & 0xff;
				int blue = (pixel) & 0xff;
				System.out
						.println("R: " + red + " G: " + green + " B: " + blue);

			}
		}

		try {
			ImageIO.write(image, "png", new File("test.png"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
