# Create a randomized 2-dimentional datamatrix image using Java 2D

I have implemented an algorithm today for creating a random datamatrix image. While writing the algorithm I learned about how to create a random image using a BufferedImage, how to iterate the bits in a byte array, how to do simple bitwise calculation and image scaling; The result of the algorithm is images similar to these ones:

Here is the code:

private byte[] createRandomDataMatrixImage(int height, int width) throws IOException {
byte[] tmp = new byte[height * width];
BufferedImage img = new BufferedImage(180, 180, BufferedImage.TYPE_INT_ARGB);

Graphics2D g = img.createGraphics();
g.setBackground(Color.BLACK);
g.setColor(Color.BLACK);

int x = 0, y = 0, bits = 0;
int bwidth = 10;

Random random = new Random();
random.nextBytes(tmp);

String string = new String(tmp);

g.setBackground(Color.BLACK);
g.setColor(Color.BLACK);

for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);

for (int j= 0; j < 8; ++j) {
int b = ((c >> j) & 1);
if (b == 1) {
g.fillRect(x, y, bwidth, bwidth);
}
x += bwidth;

bits++;
if ((bits % 18) == 0) {
x = 0;
y += bwidth;
bits = 0;
}
}
}

g.drawImage(img, 0, 0, 180, 180, null);

BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaled.createGraphics();
g2.drawImage(img, 0, 0, width, height, null);

ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(scaled, "png", out);

return out.toByteArray();
}

Each execution of the function will produce a new random image. I’ll leave it up to you to experiment with the codes. You could for instance draw other shapes and figures instead of the standard rectangel and also change the colors. The BufferedImage type (ARGB) used in this code contains a alpha channel as well, which makes the produced image transparent.

How the image is produced:

– create an empty BufferedImage
– fill an byte array with random bytes
– convert the byte array into a String
– loop through each character
– then loop through each singel bit
– for each bit which is set (that is 1), draw a square
– continue the process until each character are converted
– on each row in the image, we only draw 18 squares
– draw the final image as a 180×180 image
– finally scale the image into desired dimension and return its bytes