Attention! Do you have any ideas for reorganizing and updating the Mapki? Please leave a note here. Thank you!

Automatic Tile Cutter

From Google Mapki

Jump to: navigation, search


This code is verified as functional. This code was written by Will James of onNYTurf.com and is designed to work in conjunction with the scipts that allow you to Add Your Own Custom Map. Note that the Automatic Tile Cutter works with both v1 and v2 of the GMaps API, but requires a bit of adjustment in order to work with v2. See the section on how to figure out values for your tiles.


Contents

[edit] Overview

Google Maps are made of dozens to thousands of tile images, depending on the zoom level. At the distant zoom levels you only need a few images to cover a large area. For example, the NYC Subway Map uses 49 images to cover the greater metropolitan area at zoom level 5. But at the closer zoom levels, thousands of images are required. It takes more than 3500 images to cover the NYC metropolitan area at zoom level 2.

Creating and then uniquely naming each of these images would be a daunting task if you had to do it by hand. That's why we use a script to do this. The following will show you how to configure a batch processing script to use with Photoshop 7 or CS that will carve all the tiles you need from one big image into hundreds of smaller GIFs, and name them exactly as you need them named.

Note: Photoshop 7 does not automatically include Javascript support. You will need to install a plugin to run Javascript. The plugin is available for Mac and Windows.

[edit] The Google Map Tile Structure

Before we set up and use our script we need to know a few things about Google's tiles.

As we learned earlier, each Tile has a Latitude Longitude and Zoom Value.
These are represented by x, y, and z.

Here is what a tile path from Google looks like:

http://mt.google.com/mt?v=w2.5&x=1204&y=1536&zoom=5

As you can see this image has the following values:

x=1206	y=1539	zoom=5

Every Tile is 256 pixels x 256 pixels.

[edit] How to Figure Out the Values for Your Tiles

so how do you get the x, y, z, values?'

[AUTHOR's UPDATE: There is a new tool which makes getting all the following even easier: With this tool, you can load your own image, scale it to the right size and position it over Google's tiles, and it will give you all the relative information you need to know to scale, place, cut and name your tiles. However, you should still read through this whole tutorial as the tool does not explain exactly how to use the information. This tutorial is not writen with that tool in mind, but you should be able to figure out the connection. If someone has the time and would like to re-write this tutorial before I get to it, by all means go to it. -Will ]

Fortunately you don'?t have to get ALL the x, y, and z values for all your images. We only need to get a set of values for ONE tile and from there we can derive all the other values we need.

We start with a limited area for our map because we assume you don'?t want to remap the whole world, but just a small corner of it. All we need then is to get the x, y, and z value of the upper left corner tile of our map area and know how many tiles wide and high our map area is. For simplicity our example map is square so that the area width and height are the same, but you could tweak this script to work with rectangular areas. Once we know the upper left corner tile values, our batch processing script will calculate the rest for us.

Unfortunately getting just these corner tile values is not easy on our own.

Fortunately again there is a tool that will help do this for us. This tool will help us figure out this information for the upper left corner tile values.

[AUTHOR's NOTE: as mentioned above, also see this tool]

Using the map on the tool page you can find the center of your map area. When you click on the map, the webpage will get the latitude and longitude for the center of your map. You can also set the zoom level and tile width here. The website will return Google's tiles that make up your requested map area. For our batch processing script you will want to do this for your furthest zoom level. You'?ll probably have to experiment a little till you get the right values that match your map area. For my NYC Subway map my furthest zoom level is 5 and my tile width is 7. Your maximum zoom level will probably be somewhere between 5 and 8.

To get the values for the upper left corner tile, we now just right click on that tile and select view image. This will load the image into the browser window, and now we can see our x, y, and zoom values in the image url. The image source will look something like this:

http://mt.google.com/mt?v=w2.5&x=1204&y=1536&zoom=5

Whew. So there it is. Our start values for this example are:

x = 1204   
y = 1536   
zoom = 5 
tile width = 7

[NOTE FOR GOOGLE MAPS API v2: The output from both of the tile tools listed above will not work for v2. But don't fret; it's an easy adjustment to get the figures to work. Version 2 reverses the zoom levels from version 1 in order to allow an infinite level of zoom inwards; instead of zoom level 18 representing the maximum zoom out (the view where you can see the most of the map), it's level 0. So in order to get the correct filenames for your tiles, simply subtract the zoom level given from 17. In the example above, instead of zoom = 5, you'd get zoom = 12.]

[edit] Configuring The Script

The batch processing script provided is too long to go through in detail here. This tutorial focuses on showing you how to configure it for your map area so you can make your tiles.

To use the script provided you must enter some custom values, including the ones we just got for our upper left hand tile. The values you must customize come at the beginning of the script.

[edit] Zoom Level

Last things first. The first variable you encounter sets the Zoom Level you want to generate tiles for. To create your custom map you will probably want tiles at various levels. For each level you want to create tiles for, you must change this value and rerun the batch processing script on your master art. Here it is set to 3, but you will change this every time you want to run this script for another level.

var ZoomLevel = 3;  

The rest of the variables you must customize you will only customize once for your map area. Lets go through them one by one:

[edit] Folder Path

This next one sets the path to where your tiles will be saved. This path is for use on a PC. The path on the Mac will be slightly different (typical example: ~/Desktop/). This sample path uses a separate folder for each zoom level. Those folders are in a folder 'GoogleMap' that sits on the user desktop. You will have to pre-create your zoom folders, but the path to those folders is dynamically generated in this example. You will also need to change 'username' here to whatever username you have on your computer.

var FolderPath = "/Documents and Settings/username/Desktop/GoogleMap/Zoom"+ZoomLevel+"Maps/";

[edit] Furthest Zoom Upper Left Corner Values

Put those upper left corner values we got to work. These are the originating values off of which the batch processing script will figure out the values for all the tiles you are creating.

var OrgX = 1204;   //<-- the X value
var OrgY = 1536;   //<-- the Y value
var OrgZoomLevel = 5;   //<-- the zoom level
var OrgTileWidth = 7;    //<-- the number of tiles wide your full map area is
var OrgTileHeight = 7;    //<-- the number of tiles high your full map area is

[edit] Transparency

Set this value to true if you are slicing an image with transparencies. If set to false, the transparencies will not be in the tiles. Setting to true might be slower so it may be best to set to false if you don't want your tiles to be transparent.

var Transparency = true; //<-- true if slicing file with transparencies, false if not as this is slower

That's all you have to configure! Here is how the whole thing looks with our customized values at the top:

[edit] The Script

/*  Tile Carver for Photoshop 7
   and Probably CS :)  
   Created by Will James 
   http://onNYTurf.com

   Transparency option added by
   Curtis Wyatt
   http://gocalipso.com/
*/


//**** YOU SHOULD CUSTOMIZE THE FOLLOWING VARIABLE DEPENDING ON YOUR NEED ****
var ZoomLevel = 5;  //<-- Enter the zoom level we want to create tiles for

var FolderPath = "/Documents and Settings/username/Desktop/GoogleMap/Zoom"+ZoomLevel+"Maps/";  //<-- path to where we will save our tiles

// We start with the coordinates, zoom, and width of an upper left corner tile and generate everything from there
// We can calculate new tile values from these values for any zoom level without having to look up these details for each.
var OrgX = 1204;   //<-- the X value
var OrgY = 1536;   //<-- the Y value
var OrgZoomLevel = 5;   //<-- the zoom level
var OrgTileWidth = 7;    //<-- the number of tiles wide your full map area is
var OrgTileHeight = 7;    //<-- the number of tiles high your full map area is

var Transparency = true;  //<-- true if slicing file with transparencies, and you want to retain them, false if not as this  is slower

//**** EVERYTHING BEYOND HERE SHOULD NOT BE TOUCHED UNLESS YOU KNOW WHAT YOU ARE DOING!!!

// Exponent Function 
// we will need these later
function PowMe(a, b){
   var o = a;
   for (n = 1; n < b; n++){ o *= a; }
   if (b==0){ o = 1;    }
   return o;
};

// via http://www.ps-scripts.com/bb/viewtopic.php?p=343
function takeSnapshot () { 
    var id686 = charIDToTypeID( "Mk  " ); 
    var desc153 = new ActionDescriptor(); 
    var id687 = charIDToTypeID( "null" ); 
    var ref119 = new ActionReference(); 
    var id688 = charIDToTypeID( "SnpS" ); 
    ref119.putClass( id688 ); 
    desc153.putReference( id687, ref119 ); 
    var id689 = charIDToTypeID( "From" ); 
    var ref120 = new ActionReference(); 
    var id690 = charIDToTypeID( "HstS" ); 
    var id691 = charIDToTypeID( "CrnH" ); 
    ref120.putProperty( id690, id691 ); 
    desc153.putReference( id689, ref120 ); 
    executeAction( id686, desc153, DialogModes.NO ); 
} 

function revertToLastSnapshot() { 
    var docRef = app.activeDocument; 
    var hsObj = docRef.historyStates; 
    var hsLength = hsObj.length; 
    for (var i = hsLength-1; i > -1; i--) { 
        if(hsObj[i].snapshot) { 
            docRef.activeHistoryState = hsObj.getByName('Snapshot ' + i); 
            break; 
        }       
    }       
} 


var StartX = OrgX*PowMe(2,(OrgZoomLevel - ZoomLevel)); //******this will work as long as your ORG values are your furthest zoom*******
var StartY = OrgY*PowMe(2,(OrgZoomLevel - ZoomLevel));  //******this will work as long as your ORG values are your furthest zoom*******

var xTiles = OrgTileWidth*PowMe(2,(OrgZoomLevel - ZoomLevel)); //<-- calculate the number of tiles across
var yTiles = OrgTileHeight*PowMe(2,(OrgZoomLevel - ZoomLevel)); //<-- calculate the number of tiles down

var PixelWidth = 256; //<-- Set by Google
var PixelHeight = 256; //<-- Set by Google and same as width, but we included to make it easier to understand how this script works

var TotalTiles = xTiles * yTiles;  //<-- calculate the total number of tiles

// Before we start cutting up images we make sure Photoshop is measuring things in terms of Pixels
preferences.rulerUnits = Units.PIXELS;

// Counters to track which x value and which y value we are on in our image tile grid
var xm = 0;
var ym = 0;

var TileX = StartX; //<-- Set out first Google X value - later used in file name
var TileY = StartY; //<-- Set out first Google Y value - later used in file name

// Cut 'em up
// For each tile we need to make, we repeat each step in this loop
for (n=1; n<TotalTiles+1; n++) {            
    
    // We cut up tiles column by column
    // I.E. we cut up all the tiles for a given x value before moving on to the next x value.
    // We do this by checking if the y value we are on is the last tile in a column 
    // We compare our y counter to our total y number of Tiles, if they are the same is we do the following
    if (ym == yTiles){   
        xm += 1; //<-- Up the x value by 1, i.e. we move over to the next column   
        ym = 0;  //<-- Reset the y value to 0 so we start back at the top of our new column
        TileX += 1; //<-- Increase our Google X value for our file name 
        TileY = StartY;  //We reset our Google Y value for out file name everytime we change columns
    };
    
    // Based on our our TileWidth and TileHeight and the column we are on we determine our selection origin and area values     
    MyXO = xm*(PixelWidth);
    MyXL = xm*(PixelWidth)+(PixelWidth);
    MyYO = ym*(PixelHeight);
    MyYL = ym*(PixelHeight)+(PixelHeight);                
    
    // We make sure our source image is the active document
    var srcDoc = activeDocument;
    
    //Select Area and Copy
    srcDoc.selection.select(Array (Array(MyXO, MyYO), Array(MyXL, MyYO), Array(MyXL, MyYL), Array(MyXO, MyYL)), SelectionType.REPLACE, 0, false);    
    
    if (Transparency) {
        takeSnapshot();
        srcDoc.crop(Array(MyXO, MyYO, MyXL, MyYL));
        //Save New Doc
        var saveMe = activeDocument;
                 
        //Set path to file and file name
        saveFile = new File(FolderPath + TileX+ "_" + TileY+ "_" + ZoomLevel + ".gif");    
        //Set save options
        gifSaveOptions = new GIFSaveOptions();
        gifSaveOptions.colors = 64;
        gifSaveOptions.dither = Dither.NONE;
        gifSaveOptions.matte = MatteType.NONE;
        gifSaveOptions.preserveExactColors = 0;
        gifSaveOptions.transparency = 1;
        gifSaveOptions.interlaced = 0;
        
        //Save the file and close it
        saveMe.saveAs(saveFile, gifSaveOptions, true, Extension.LOWERCASE);
        revertToLastSnapshot();
        //saveMe.close(SaveOptions.DONOTSAVECHANGES);
    }
    else {
        srcDoc.selection.copy();
        
        //Paste to new Doc
        var pasteDoc = documents.add(PixelWidth, PixelHeight, srcDoc.resolution, "Paste Target");
        pasteDoc.paste();
        pasteDoc = null;
        //Save New Doc
        var saveMe = activeDocument;
        
        //Flatten
        saveMe.flatten();
        
        //Set path to file and file name
        saveFile = new File(FolderPath + TileX+ "_" + TileY+ "_" + ZoomLevel + ".gif");    
        //Set save options
        gifSaveOptions = new GIFSaveOptions();
        gifSaveOptions.colors = 64;
        gifSaveOptions.dither = Dither.NONE;
        gifSaveOptions.matte = MatteType.NONE;
        gifSaveOptions.preserveExactColors = 0;
        gifSaveOptions.transparency = 0;
        gifSaveOptions.interlaced = 0;
        
        //Save the file and close it
        saveMe.saveAs(saveFile, gifSaveOptions, true,Extension.LOWERCASE);
        saveMe.close(SaveOptions.DONOTSAVECHANGES);
    }
    
    //Advance Y counter for next image
    ym += 1;
    
    //Advance Google Y value for next image name
    TileY += 1;
}

[edit] Version 2 Depth Reversal Fix

I'm new to the maps API, but I hear that in the original version, the zoom levels were in the range 0 to 17, with 17 being the furthest out. In version 2, it seems 0 is the furthest out, and the number of zoom levels is unlimited. It appears this script was written for version 1. For v2 compatibility, multiply the difference between original and current zoom level by -1, so that the difference is positive.

   var StartX = OrgX*PowMe(2,-1*(OrgZoomLevel - ZoomLevel)); 
   var StartY = OrgY*PowMe(2,-1*(OrgZoomLevel - ZoomLevel)); 
   var xTiles = OrgTileWidth*PowMe(2,-1*(OrgZoomLevel - ZoomLevel)); 
   var yTiles = OrgTileHeight*PowMe(2,-1*(OrgZoomLevel - ZoomLevel));

[edit] Updated Script

The script has been updated to support creating tiles for multiple zoom levels at once, to automatically add padding where necessary (removes the necessity to specify OrgTileWidth and OrgTileHeight), to save as PNG, JPEG, and/or GIF, and to operate much faster (even with multiple layers and transparencies). The following has only been tested with Photoshop CS3.

/*  Tile Carver for Photoshop (modified by Nate, only tested in CS3)
  Created by Will James 
  http://onNYTurf.com

  Transparency option added by
  Curtis Wyatt
  http://gocalipso.com/

  Hacked apart and updated to add support for creating multiple zoom levels at once
  Automatically adds extra tiles/pixels where needed
  Can save as PNG, JPEG, and/or GIF
  Now operates much faster with multiple layers/transparencies
  Nate Bundy
  http://www.lemonrage.com/
*/

//**** YOU SHOULD CUSTOMIZE THE FOLLOWING VARIABLE DEPENDING ON YOUR NEED ****
var HighestZoomLevel = 17; // Enter the highest zoom level we are creating tiles for (should be less than OrgZoom; technically the  script should be able to handle values larger as well, but your image quality will suffer)
var LowestZoomLevel = 12; // Enter the last zoom level we want to create tiles for (must be <= HighestZoomLevel for the script to do anything)

var FolderPath = "C:/Users/test/";  //<-- path to where we will save our tiles

// We start with the coordinates, zoom, and width of an upper left corner tile and generate everything from there
// We can calculate new tile values from these values for any zoom level without having to look up these details for each.
var OrgX = 31551;   // the Google Maps X value of the tile at the top left corner of your Photoshop document
var OrgY = 50899;   // the Google Maps Y value of the tile at the top left corner of your Photoshop document
var OrgZoomLevel = 17;   // the Google Maps zoom level of your Photoshop document (for best results, you will need to resize your  Photoshop document to match a zoom level as closely as possible before running this script)
var PixelWidth = 256; // Your width and height should be 256 unless you override Google's default in a custom map type
var PixelHeight = 256;

// set each file type to true that you wish the script to save out. you may save out all three at the same time if you wish
var saveJPEG = true;
var savePNG = false;
var saveGIF = false;

// Note (by Nate): I've dramatically increased the speed of the transparent path. It's even faster than the old transparency=false  path now. Taking unnecessary snapshots was slowing the transparent path down quite a bit. Now the main speed limiter is saving each tile out to disk, and I doubt there's a way to speed that up.

//**** EVERYTHING BEYOND HERE SHOULD NOT BE TOUCHED UNLESS YOU KNOW WHAT YOU ARE DOING!!!

// Exponent Function 
// we will need these later
/*function PowMe(a, b){
  var o = a;
  for (n = 1; n < b; n++){ o *= a; }
  if (b==0){ o = 1;    }
  return o;
};*/
// why the custom power function? switched to built in Math.pow()

var currentDocument = app.activeDocument; // Run the script on the active document

// via http://www.ps-scripts.com/bb/viewtopic.php?p=343
function takeSnapshot () { 
   var id686 = charIDToTypeID( "Mk  " ); 
   var desc153 = new ActionDescriptor(); 
   var id687 = charIDToTypeID( "null" ); 
   var ref119 = new ActionReference(); 
   var id688 = charIDToTypeID( "SnpS" ); 
   ref119.putClass( id688 ); 
   desc153.putReference( id687, ref119 ); 
   var id689 = charIDToTypeID( "From" ); 
   var ref120 = new ActionReference(); 
   var id690 = charIDToTypeID( "HstS" ); 
   var id691 = charIDToTypeID( "CrnH" ); 
   ref120.putProperty( id690, id691 ); 
   desc153.putReference( id689, ref120 ); 
   executeAction( id686, desc153, DialogModes.NO ); 
}

function revertToLastSnapshot() { 
   var docRef = app.activeDocument; 
   var hsObj = docRef.historyStates; 
   var hsLength = hsObj.length; 
   for (var i = hsLength-1; i > -1; i--) { 
       if(hsObj[i].snapshot) { 
           docRef.activeHistoryState = hsObj.getByName('Snapshot ' + i); 
           break;
       }       
   }       
}

function revertToSnapshot(snapshotID) {
  currentDocument.activeHistoryState = currentDocument.historyStates[snapshotID];
}

function getLastSnapshotID()
{ 
   var docRef = app.activeDocument; 
   var hsObj = docRef.historyStates; 
   var hsLength = hsObj.length; 
   for (var i = hsLength-1; i > -1; i--) { 
       if(hsObj[i].snapshot) { 
           return i; 
           break;
       }       
   }       
}

function getVisibleLayers(doc)
{
	var tempArray = new Array();
	for (var i = 0; i < doc.layers.length; i++)
	{
		if (doc.layers[i].visible)
			tempArray.push(i);
	}
	return tempArray;
}

function isLayerEmpty(doc, layer)
{
  if (!doc) {
    doc = app.activeDocument;
  }
  if (!layer) {
    layer = doc.activeLayer;
  }
  return parseInt(layer.bounds.toString().replace(/\D/g,"")) == 0;
}

function visibleLayersEmpty(doc)
{
	var bool = true;
	if (!doc) {
		doc = app.activeDocument;
	}
	for (var i = 0; i < visibleLayers.length; i++)
	{
		bool = isLayerEmpty(doc, doc.layers[visibleLayers[i]]);
		if (!bool)
			return bool;
	}
	return bool;
}

var startRulerUnits = app.preferences.rulerUnits; // Save the current preferences
app.preferences.rulerUnits = Units.PIXELS; // Set Photoshop to use pixels

// Find the visible layers
var visibleLayers = getVisibleLayers(currentDocument);

var ZoomLevel = HighestZoomLevel;
var LastZoomLevel = OrgZoomLevel;	
var CurrentX = OrgX;
var CurrentY = OrgY;

// Take initial snapshot. We'll go back to this once we're finished to leave the document in the state we started
// TODO: I'm not sure how to delete snapshots, but I'd like to do that in the future as well to leave the document EXACTLY as we opened it
takeSnapshot();
var InitialSnapshotID = getLastSnapshotID();

// Do the following for each zoom level the user wants
while (ZoomLevel >= LowestZoomLevel)
{
	// add padding to make starting X and Y tile values divisible by 2^(LastZoomLevel - DesiredZoom)
	
	// first, get X and Y values needed for previous zoom level to resize properly to next zoom level we're outputting
	var ExpectedX = Math.floor(CurrentX / Math.pow(2, LastZoomLevel - ZoomLevel));
	var NewX = ExpectedX * Math.pow(2, LastZoomLevel - ZoomLevel);

	var ExpectedY = Math.floor(CurrentY / Math.pow(2, LastZoomLevel - ZoomLevel));
	var NewY = ExpectedY * Math.pow(2, LastZoomLevel - ZoomLevel);
	
	var XTilesNeeded = CurrentX - NewX;
	var YTilesNeeded = CurrentY - NewY;
 
	// Now add padding for the extra tiles needed
	currentDocument.resizeCanvas(currentDocument.width.value + (XTilesNeeded * PixelWidth), currentDocument.height.value + (YTilesNeeded * PixelHeight), AnchorPosition.BOTTOMRIGHT);

	CurrentX = ExpectedX;
	CurrentY = ExpectedY;
	
	// Ensure total width and height of canvas is a multiple of PixelWidth and PixelHeight respectively
	var BottomPaddingNeeded = (Math.ceil(currentDocument.height.value / PixelHeight) * PixelHeight) - currentDocument.height.value;
	var RightPaddingNeeded = (Math.ceil(currentDocument.width.value / PixelWidth) * PixelWidth) - currentDocument.width.value;
	currentDocument.resizeCanvas(currentDocument.width.value + RightPaddingNeeded, currentDocument.height.value + BottomPaddingNeeded, AnchorPosition.TOPLEFT);
	
	// Add padding to make number of tiles divisible by 2^(LastZoomLevel - DesiredZoom)
	var NumXTiles = currentDocument.width.value / PixelWidth;
	var NumYTiles = currentDocument.height.value / PixelHeight;
	var NumXTilesNeeded = Math.ceil(NumXTiles / Math.pow(2, LastZoomLevel - ZoomLevel)) * Math.pow(2, LastZoomLevel - ZoomLevel);
	var NumYTilesNeeded = Math.ceil(NumYTiles / Math.pow(2, LastZoomLevel - ZoomLevel)) * Math.pow(2, LastZoomLevel - ZoomLevel);
	NumXTilesNeeded = NumXTilesNeeded - NumXTiles;
	NumYTilesNeeded = NumYTilesNeeded - NumYTiles;
	currentDocument.resizeCanvas(currentDocument.width.value + (NumXTilesNeeded * PixelWidth), currentDocument.height.value + (NumYTilesNeeded * PixelHeight), AnchorPosition.TOPLEFT);
	NumXTiles = NumXTiles + NumXTilesNeeded;
	NumYTiles = NumYTiles + NumYTilesNeeded;
	
	// Now resize the canvas and image by .5^(LastZoomLevel - ZoomLevel) (Decrease size by 50% for each zoom level)
	if (ZoomLevel < LastZoomLevel)
	{
		var ResizeFactor = Math.pow(0.5, (LastZoomLevel - ZoomLevel));
		currentDocument.resizeImage(currentDocument.width.value * ResizeFactor, currentDocument.height.value * ResizeFactor);
	}
	
	// Now that we're done resizing the image and canvas, take a snapshot for this zoom level
	takeSnapshot();
	var ZoomLevelSnapshotID = getLastSnapshotID();
	
	var StartX = CurrentX; 
	var StartY = CurrentY;
	
	var xTiles = parseInt(currentDocument.width.value, 10) / PixelWidth;
	var yTiles = parseInt(currentDocument.height.value, 10) / PixelHeight;
	   	
	var TotalTiles = xTiles * yTiles;  //<-- calculate the total number of tiles
	
	// Counters to track which x value and which y value we are on in our image tile grid
	var xm = 0;
	var ym = 0;
	
	var TileX = StartX; //<-- Set out first Google X value - later used in file name
	var TileY = StartY; //<-- Set out first Google Y value - later used in file name
	
	// Cut 'em up
	// For each tile we need to make, we repeat each step in this loop
	for (n=1; n<TotalTiles+1; n++)
	{            
		// We cut up tiles column by column
		// I.E. we cut up all the tiles for a given x value before moving on to the next x value.
		// We do this by checking if the y value we are on is the last tile in a column 
		// We compare our y counter to our total y number of Tiles, if they are the same is we do the following
		if (parseInt(ym, 10) == parseInt(yTiles, 10))
		{   
			xm += 1; //<-- Up the x value by 1, i.e. we move over to the next column   
			ym = 0;  //<-- Reset the y value to 0 so we start back at the top of our new column
			TileX += 1; //<-- Increase our Google X value for our file name 
			TileY = StartY;  //We reset our Google Y value for out file name everytime we change columns
		}
		
		// Based on our our TileWidth and TileHeight and the column we are on we determine our selection origin and area values     
		MyXO = xm*(PixelWidth);
		MyXL = xm*(PixelWidth)+(PixelWidth);
		MyYO = ym*(PixelHeight);
		MyYL = ym*(PixelHeight)+(PixelHeight);                
						
		//try {
			currentDocument.crop(Array(MyXO, MyYO, MyXL, MyYL));
		/*}
		catch (e)
		{
			alert("xm: " + xm + ", ym: " + ym + ", MyXO: " + MyXO + ", MyYO: " + MyYO + ", MyXL: " + MyXL + ", MyYL: " + MyYL + ", XTiles: " + xTiles + ", YTiles: " + yTiles + "ym == yTiles?: " + (ym == yTiles));
		}*/
		
		if (!visibleLayersEmpty(currentDocument))
		{
			//Save New Doc
			var saveMe = currentDocument;
								
			//Save the file
			if (saveGIF)
			{
				//Set path to file and file name
				saveFile = new File(FolderPath + ZoomLevel + "_" + TileX + "_" + TileY + ".gif");    
				//Set save options
				gifSaveOptions = new GIFSaveOptions();
				gifSaveOptions.colors = 64;
				gifSaveOptions.dither = Dither.NONE;
				gifSaveOptions.matte = MatteType.NONE;
				gifSaveOptions.preserveExactColors = 0;
				gifSaveOptions.transparency = 1;
				gifSaveOptions.interlaced = 0;
				saveMe.saveAs(saveFile, gifSaveOptions, true, Extension.LOWERCASE);
			}
			if (savePNG)
			{
				//Set path to file and file name
				saveFile = new File(FolderPath + ZoomLevel + "_" + TileX + "_" + TileY + ".png");    
				pngSaveOptions = new PNGSaveOptions();
				pngSaveOptions.interlaced = 0;
				saveMe.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
			}
			if (saveJPEG)
			{
				//Set path to file and file name
				saveFile = new File(FolderPath + ZoomLevel + "_" + TileX + "_" + TileY + ".jpg");    
				jpegSaveOptions = new JPEGSaveOptions();
				jpegSaveOptions.formatOpsions = FormatOptions.STANDARDBASELINE;
				jpegSaveOptions.matte = MatteType.NONE;
				jpegSaveOptions.quality = 5;				
				saveMe.saveAs(saveFile, jpegSaveOptions, true, Extension.LOWERCASE);
			}
		}
		revertToSnapshot(ZoomLevelSnapshotID);
		//saveMe.close(SaveOptions.DONOTSAVECHANGES);
	
		//Advance Y counter for next image
		ym += 1;
		
		//Advance Google Y value for next image name
		TileY += 1;
	}
	//revertToLastSnapshot(); 
	LastZoomLevel = ZoomLevel;
	ZoomLevel--;
}
// Leave the document as we opened it
revertToSnapshot(InitialSnapshotID);

// Restore application preferences
app.preferences.rulerUnits = startRulerUnits;

Personal tools
Advertisement