Click here to Skip to main content
15,885,216 members
Articles / Mobile Apps / Android

Texture Atlas Maker

Rate me:
Please Sign up or sign in to vote.
4.94/5 (16 votes)
1 Apr 2012BSD6 min read 142.2K   7K   55  
A utility to create texture atlases for 2D OpenGL games
/*
Copyright (c) 2012, Ed Welch
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

*    Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*    Redistributions in binary form must reproduce the above copyright notice, this list of conditions 
     and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


public class AtlasImage 
{
	private int xBorder;
	private int yBorder;
	private int x;
	private int y;
	private int xOffset;
	private int yOffset;
	private int transWidth;
	private int transHeight;
	private boolean transparent;
	private BufferedImage image;
	private String fileName;
	public AtlasImage()
	{
		xBorder = 0;
		yBorder = 0;
	}
	public void setXBorder(int xBorder)
	{
		this.xBorder = xBorder;
	}
	public void setYBorder(int yBorder)
	{
		this.yBorder = yBorder;
	}
	public boolean isTransparent()
	{
		return transparent;
	}
	public void Load(String strDir, String fileName) throws IOException
	{
	    File file = new File(strDir + File.separator + fileName);
	    image = ImageIO.read(file);
	    this.fileName = fileName.substring(0, fileName.length()-4);
	}
	public BufferedImage getImage()
	{
		return image;
	}
	public int getNumPixels()
	{
		return getWidth()*getHeight();
	}
	public int getSizeScore()
	{
		int width = getWidth();
		int height = getHeight();
		double aspectRatio;
		if (width > height)
			aspectRatio = (double)width*width / height;
		else
			aspectRatio = (double)height*height / width;
		return height * width + (int)(aspectRatio*0.1);
	}
	public boolean pointInside(int xTest, int yTest)
	{
		return xTest > x && xTest < x + getWidth() &&
				yTest > y && yTest < y + getHeight();
	}
	public int getHeight()
	{
		return image.getHeight()+xBorder;
	}
	public int getWidth()
	{
		return image.getWidth()+yBorder;
	}	
	public int getBottom()
	{
		return y + image.getHeight();
	}
	public int getRight()
	{
		return x + image.getWidth();
	}
	public void setImage(BufferedImage image)
	{
		this.image = image;
	}
	public void draw(Graphics2D g)
	{
        g.drawImage(image, null, x, y);		
	}
	public void drawWithBorder(Graphics2D g)
	{
        g.drawImage(image, null, x, y);		
        g.drawRect(x, y, getWidth()-1-xBorder, getHeight()-1-yBorder);
	}
	public int getX()
	{
		return x;
	}
	public void setX(int x)
	{
		this.x = x;
	}
	public int getY()
	{
		return y;
	}
	public void setY(int y)
	{
		this.y = y;
	}
	public void setXY(int x, int y)
	{
		this.x = x;
		this.y = y;
	}
	public boolean CropTransparent(int alphaThresh) 
	{
		transWidth = image.getWidth(null);
		transHeight = image.getHeight(null);
		if (transWidth == 0 || transHeight == 0) return false;  
		int[] srcPixels;
		try
		{
			srcPixels = new int[transWidth*transHeight];
		}
		catch (OutOfMemoryError e) 
		{
			return true;
		}
	    image.getRGB(0, 0, transWidth, transHeight, srcPixels, 0, transWidth);
	    
		int srcX, srcY;
		int alpha;
		int xFirst = transWidth+1;
		int xLast = -1;
		int yFirst = transHeight+1;
		int yLast = -1;
		transparent = false;
		for (srcY = 0; srcY < transHeight; ++srcY) 
		{
			for (srcX = 0; srcX < transWidth; ++srcX) 
			{
				alpha = (srcPixels[srcX + srcY * transWidth] >>24) & 0xff;
				if (alpha > alphaThresh)
				{
					if (xLast < srcX) xLast = srcX;  
					if (xFirst > srcX) xFirst = srcX;  
					if (yLast < srcY) yLast = srcY;  
					if (yFirst > srcY) yFirst = srcY;  
				}
				if (alpha < 255)
				{
					transparent = true;
				}
			}
		}
		int opaqueWidth = xLast-xFirst+1;
		int opaqueHeight = yLast-yFirst+1;
		if (opaqueWidth < 1 || opaqueHeight < 1)
		{
	        xOffset = 0;
	        yOffset = 0;
	        opaqueWidth = 1;
	        opaqueHeight = 1;
	        System.out.println("Warning: image with no opaque pixels!" + fileName);
	        return false;
		}
		else
		{
	        xOffset = xFirst;
	        yOffset = yFirst;
		}
		
		BufferedImage imageCut;
        imageCut = new BufferedImage(opaqueWidth, opaqueHeight, 
        		BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = imageCut.createGraphics();
        g.drawImage(image, null, -xOffset, -yOffset);		
        g.dispose();
		image = imageCut;
		return true;
	}

	public String GetSerialize() 
	{
//		String str = "image name="+fileName + " x=" + x + " y=" + y + 
//		" width=" + opaqueWidth + " height=" + opaqueHeight;
//		if (xOffset != 0) str += " xOffset=" + xOffset;
//		if (yOffset != 0) str += " yOffset=" + yOffset;
//		if (opaqueWidth != transWidth) str += " transWidth=" + transWidth;
//		if (opaqueHeight != transHeight) str += " transHeight=" + transHeight;
//		if (!transparent) str += " trans="+transparent;
		String str = "    <image name=\""+fileName + 
			"\" x=\"" + x + 
			"\" y=\"" + y + 
			"\" width=\"" + image.getWidth() + 
			"\" height=\"" + image.getHeight();
		if (xOffset != 0) str += "\" xOffset=\"" + xOffset;
		if (yOffset != 0) str += "\" yOffset=\"" + yOffset;
		if (image.getWidth() != transWidth) str += "\" transWidth=\"" + transWidth;
		if (image.getHeight() != transHeight) str += "\" transHeight=\"" + transHeight;
		if (!transparent) str += "\" trans=\""+transparent;
		str += "\"/>\n";
		return str;
	}
	public String GetSerializePlist() 
	{
		String str = "\t\t\t\t<key>"+fileName +".png</key>\n";
		str+="\t\t\t\t<dict>\n\t\t\t\t\t<key>frame</key>\n";
		str+="\t\t\t\t\t<string>{{"+x+","+y+"},{"+ image.getWidth()+","+image.getHeight()+"}}</string>\n" ;				
		if (xOffset != 0||yOffset != 0) 
			str += "\t\t\t\t\t<key>offset</key>\n\t\t\t\t\t<string>{"+ xOffset+","+yOffset+"}</string>\n";
		else
			str += "\t\t\t\t\t<key>offset</key>\n\t\t\t\t\t<string>{0,0}</string>\n";
		str += "\t\t\t\t\t<key>rotated</key>\n\t\t\t\t\t<false />\n";
		str += "\t\t\t\t\t<key>sourceColorRect</key>\n\t\t\t\t\t<string>{{0,0},{"+ image.getWidth()+","+image.getHeight()+"}}</string>\n";
		str += "\t\t\t\t\t<key>sourceSize</key>\n\t\t\t\t\t<string>{"+ image.getWidth()+","+image.getHeight()+"}</string>\n";
		str+="\t\t\t\t</dict>\n";		
		return str;		
	}
	public String getFileName()
	{
		return fileName;
	}
	public String getStats()
	{
		return fileName + ".png ("+transWidth+"x"+transHeight+")";
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer Astronautz
Spain Spain
After working in the software industry for many years, I've started my own games company that specialises in strategy games for mobile platforms.

Comments and Discussions