/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imageplayground;

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**
 *
 * @author maik
 */
public class Main {

    
    public static void main(String[] args) throws Exception {
        BufferedImage input = ImageIO.read(new File(args[0]));

        BufferedImage output = new BufferedImage(input.getWidth(), input.getHeight() * 2, BufferedImage.TYPE_INT_RGB);

        for(int x = 0; x < input.getWidth() / 8; ++x) {
            for(int y = 0; y < input.getHeight() / 8; ++y) {

                int xpos = x * 8;
                int ypos = y * 8;

                int[] block = new int[64];

                // fetch a 8x8 block of RGB data and convert to grayscale
                // also copy original picture to output
                for(int x2 = 0; x2 < 8; ++x2) {
                    for(int y2 = 0; y2 < 8; ++y2) {
                        int rgbdata = input.getRGB(xpos + x2, ypos + y2);
                        output.setRGB(xpos + x2, ypos + y2, rgbdata);
                        int gray = (rgbdata & 0xFF0000) >> 16;
                        gray += (rgbdata & 0xFF00) >> 8;
                        gray += (rgbdata & 0xFF);
                        block[x2 * 8 + y2] = gray / 3;
                    }
                }
             
                // my own stupid metric for local contrast:
                // sum of diff to previous pixel
                int avg = 0;
                for(int i = 1; i < block.length; ++i) {
                    int prev = block[i - 1];
                    int current = block[i];
                    int diff = prev - current;
                    avg += diff > 0 ? diff : -diff;
                }

                // normalize to 0...255
                avg /= 63;
                

                // let's scale things in a non-linear fashion for increased contrast
                double avgscaled = (Math.log(avg + 1)) / Math.log(256);

                // and then map it back to a 0...255 range, oh, and invert
                avg = 255 - (int)(255 * avgscaled);

                // pack as RGB
                avg += (avg << 8) + (avg << 16);

                // write 8x8 block to output with computed value
                for(int x2 = 0; x2 < 8; ++x2) {
                    for(int y2 = 0; y2 < 8; ++y2) {
                        int xcoord = xpos + x2;
                        int ycoord = ypos + y2 + input.getHeight();
                        output.setRGB(xcoord, ycoord, avg);

                    }
                }

            }
        }

        ImageIO.write(output, "png", new File("/tmp/test.png"));

    }

}

