Skip to content

Instantly share code, notes, and snippets.

@ixtli
Created May 30, 2013 05:35
Show Gist options
  • Save ixtli/5675892 to your computer and use it in GitHub Desktop.
Save ixtli/5675892 to your computer and use it in GitHub Desktop.
Correctly samples this image: http://24.media.tumblr.com/33afdde66541395bbb3f9c8818be943a/tumblr_mmd4ozTT2g1qbgkkto1_1280.png (expected "thing.png") and outputs a "1:1" version called "deflate.png" and an explanatory reference called "grid.png"
#!/usr/bin/python
import Image;
import math;
img = Image.open("thing.png");
pixels = img.load();
width = img.size[0];
height = img.size[1];
pixelSize = 7.222222; # this is fiddly bit
halfPixel = math.ceil(pixelSize / 2);
pixelsWide = int(math.floor(width / pixelSize));
pixelsHigh = int(math.floor(height / pixelSize));
# make a new image the size of the deflation
out = Image.new("RGBA", (pixelsWide, pixelsHigh), "white");
newPixels = out.load();
accumX = 0;
accumY = 0;
for y in range(pixelsHigh):
for x in range(pixelsWide):
# Accumulation is the key
accumX = accumX + pixelSize;
accumY = accumY + pixelSize;
# The round function is the lock
newx = int(round(x * pixelSize) + halfPixel);
newy = int(round(y * pixelSize) + halfPixel);
# Display
newPixels[x, y] = pixels[newx, newy];
pixels[newx, newy] = (255,0,0,255);
img.save("grid.png", 'PNG');
out.save("deflate.png", 'PNG');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment