package eu.sorescu.ui;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class Digitizer {
private static int BORDER = 0xff00ffff;
private static int ZERO = 0xff0000ff;
private static int ONE = 0xff00ff00;
public static void main(String[] args) throws AWTException, IOException {
Robot robot = new Robot();
Dimension rectangle = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, rectangle.width * 2, rectangle.height));
getData(image).forEach(bytes ->
System.out.println(new String(bytes)));
}
private static java.util.List<byte[]> getData(BufferedImage image) throws IOException {
List<Point> startPoints = getCandidateStartPoints(image);
List<byte[]> result = new LinkedList<>();
for (Point startPoint : startPoints)
result.add(getData(image, getFrame(image, startPoint)));
return result;
}
private static java.util.List<Point> getCandidateStartPoints(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
java.util.List<Point> result = new LinkedList<>();
for (int x = 0; x < width - 1; x++) {
for (int y = 0; y < height - 1; y++) {
if (image.getRGB(x, y) != BORDER) continue;
if (image.getRGB(x + 1, y + 1) == BORDER) continue;
if (image.getRGB(x, y + 1) != BORDER) continue;
if (image.getRGB(x + 1, y) != BORDER) continue;
result.add(new Point(x, y));
}
}
return result;
}
private static Rectangle getFrame(BufferedImage image, Point start) {
Rectangle result = new Rectangle(start.x, start.y, 0, 0);
while (image.getRGB(start.x + result.width + 1, start.y) == BORDER) result.width++;
while (image.getRGB(start.x, start.y + result.height + 1) == BORDER) result.height++;
return result;
}
private static byte[] getData(BufferedImage image, Rectangle frame) throws IOException {
int bitPosition = 0;
byte value = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int y = 1; y < frame.height - 2; y++)
for (int x = 1; x < frame.width - 2; x++) {
int rgb = image.getRGB(frame.x + x, frame.y + y);
if (rgb == ZERO) {
bitPosition++;
}
if (rgb == ONE) {
value += (1 << (bitPosition));
bitPosition++;
}
if (bitPosition == 8) {
baos.write(new byte[]{value});
bitPosition = 0;
value = 0;
}
}
return baos.toByteArray();
}
}