Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
float gridSize = 20;
boolean crosshatch = true;
PImage img;
void setup() {
size(1400, 788);
pixelDensity(displayDensity());
background(255);
img = loadImage("test.jpg");
img.loadPixels();
stroke(0);
for (int y=0; y<height; y+=gridSize) {
for (int x=0; x<width; x+=gridSize) {
// average px value for that region
float b = 0;
int pxCount = 0;
for (int py=y; py<y+gridSize; py++) {
for (int px=x; px<x+gridSize; px++) {
try {
b += img.pixels[py*width + px] >> 16 & 0xFF;
pxCount += 1;
}
catch (ArrayIndexOutOfBoundsException aioobe) {
// off the end of the image, skip
}
}
}
b /= pxCount;
// single hatch
int interval = int(map(b, 0, 255, 1, gridSize/2));
if (!crosshatch) {
hatch(x, y, x+gridSize, y+gridSize, interval, false);
}
//crosshatch em
else {
// very light value = single hatch
if (b > 191) {
hatch(x, y, x+gridSize, y+gridSize, interval, false);
}
// darker = crosshatch
else {
hatch(x, y, x+gridSize, y+gridSize, interval, false);
hatch(x, y, x+gridSize, y+gridSize, interval, true);
}
}
}
}
save("output.png");
}
void hatch (float sx, float sy, float w, float h, float interval, boolean reverse) {
if (!reverse) {
float ex = sx; // end x position along start
sx = sx + interval; // offset by one interval
float ey = sy + interval; // same for end y
while (true) {
line(sx, sy, ex, ey); // draw a line at the current position
sx += interval; // start x walks across
if (sx > w) { // when it hits the edge...
sy += sx-w; // ...move down by the remainder*
sx = w; // ...and stop x
}
// * right triangle math!
// if we just add the interval to sy, we'd get
// weird gaps, but because we're at 45º, we can
// just move down by sx-w (whatever would hang
// over the right edge) and our spacing stays
// the same
ey += interval; // same for end y
if (ey > h) {
ex += ey-h;
ey = h;
}
if (ex >= sx) return;
}
}
// reversed lines
else {
float startX = sx;
sx = w-interval;
float ex = w;
float ey = sy+interval;
while (true) {
line(sx, sy, ex, ey);
sx -= interval;
if (sx < startX) {
sy += startX-sx;
sx = startX;
}
ey += interval;
if (ey > h) {
ex -= ey-h;
ey = h;
}
if (ex <= sx) return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.