Skip to content

Instantly share code, notes, and snippets.

@RandomEtc
Created November 23, 2009 21:57
Show Gist options
  • Save RandomEtc/241411 to your computer and use it in GitHub Desktop.
Save RandomEtc/241411 to your computer and use it in GitHub Desktop.
Resize big images to the nearest power of two and cut them up into 256px tiles.
String imageName = "world.topo.bathy.200401.3x5400x2700.jpg";
noSmooth();
print("opening original image... ");
PImage img = loadImage(imageName);
println("done!");
if (img.width % 256 != 0 || img.height % 256 != 0) {
println(img.width + " x " + img.height + " is not in powers of two");
float wPower = floor(log(img.width) / log(2));
int newWidth = (int)pow(2, wPower);
float hPower = floor(log(img.height) / log(2));
int newHeight = (int)pow(2, hPower);
print("resizing to powers of two: " + newWidth + " x " + newHeight + "... ");
img.resize(newWidth, newHeight);
println("done!");
}
int maxZoom = int(log(max(img.width,img.height) / 256) / log(2));
int minZoom = 1;
println("tiles will exist from zoom " + minZoom + " to zoom " + maxZoom);
PImage tile = createImage(256, 256, ARGB);
for (int zoom = maxZoom; zoom >= minZoom; zoom--) {
// size of these tiles in original image
int sourceSize = int(pow(2, maxZoom-zoom) * 256);
println("zoom " + zoom + " tiles are " + sourceSize + " x " + sourceSize + " px in original image");
int sourceWidth = int(pow(2, zoom-maxZoom) * img.width);
int sourceHeight = int(pow(2, zoom-maxZoom) * img.height);
println("img is " + sourceWidth + " x " + sourceHeight + " px at zoom " + zoom);
int numCols = max(1, sourceWidth / 256);
int numRows = max(1, sourceHeight / 256);
println("making " + numCols + " x " + numRows + " tiles...");
for (int col = 0; col < numCols; col++) {
for (int row = 0; row < numRows; row++) {
tile.copy(img, col * sourceSize, row * sourceSize, sourceSize, sourceSize, 0, 0, 256, 256);
tile.save("tiles/"+zoom+"/"+col+"/"+row+".png");
}
}
println("done!");
}
exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment