Skip to content

Instantly share code, notes, and snippets.

@bingoohuang
Created January 11, 2019 07:18
Show Gist options
  • Save bingoohuang/fa4e2a94bf77cb69e502abe6d5ee5e79 to your computer and use it in GitHub Desktop.
Save bingoohuang/fa4e2a94bf77cb69e502abe6d5ee5e79 to your computer and use it in GitHub Desktop.
create random image
package imagexx;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class RandomImage {
public static void main(String args[]) {
int width = 640;
int height = 320;
int pixelSize = 20;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int yp = height / pixelSize;
int xp = width / pixelSize;
for (int yi = 0; yi < yp; yi++) {
for (int xi = 0; xi < xp; xi++) {
int rgb = createRandomRGB();
drawPixel(img, yi, xi, pixelSize, rgb);
}
}
Graphics graphics = img.getGraphics();
graphics.setColor(Color.BLACK);
graphics.setFont(new Font("Arial", Font.BOLD, 60));
graphics.drawString("123456", 0, height/2);
try {
File f = new File("Output.png");
ImageIO.write(img, "png", f);
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
private static void drawPixel(BufferedImage img, int yi, int xi, int pixelSize, int p) {
for (int y = yi * pixelSize, yy = y + pixelSize; y < yy; y++) {
for (int x = xi * pixelSize,xx = x + pixelSize; x < xx; x++) {
img.setRGB(x, y, p);
}
}
}
private static int createRandomRGB() {
int a = (int) (Math.random() * 256); //alpha
int r = (int) (Math.random() * 256); //red
int g = (int) (Math.random() * 256); //green
int b = (int) (Math.random() * 256); //blue
return (a << 24) | (r << 16) | (g << 8) | b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment