Skip to content

Instantly share code, notes, and snippets.

@William-Lake
Last active September 18, 2017 18:45
Show Gist options
  • Select an option

  • Save William-Lake/632a8546cd33c04745c0c5e39d0fc0a7 to your computer and use it in GitHub Desktop.

Select an option

Save William-Lake/632a8546cd33c04745c0c5e39d0fc0a7 to your computer and use it in GitHub Desktop.
How to create a BufferedImage from a bunch of smaller BufferedImages.
package main;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
* Main
* <p>
* A short class for displaying how to write multiple BufferedImages to
* one larger image to create a larger image overall.
*
* I.e. Using "Tile" images to create a "Map".
*/
public class Main
{
/**
* Main Method
*/
public static void main(String[] args)
{
BufferedImage map = null;
BufferedImage tile1 = null;
BufferedImage tile2 = null;
// Load the tile images you want to use when building the map.
try
{
tile1 = ImageIO.read(Main.class.getResourceAsStream("tile1.png"));
tile2 = ImageIO.read(Main.class.getResourceAsStream("tile2.png"));
} catch (IOException ex)
{
ex.printStackTrace();
}
/*
* Create the map (I.e. the larger image)
* For the sake of this example, only creating a larger image that is two tiles wide
* by one tile tall. This is why the first parameter in "new BufferedImage(..." is
* the tile's width * 2, and the second is the tile's height.
*/
int mapWidth = tile1.getWidth() * 2;
int mapHeight = tile1.getHeight();
map = new BufferedImage(mapWidth, mapHeight, BufferedImage.TYPE_INT_ARGB);
// Get the class for painting the smaller images onto the large one.
Graphics2D g = map.createGraphics();
// Draw the first tile.
g.drawImage(tile1, 0, 0, null);
//"Translate" or "Move" to the right far enough to draw the next tile (tile2).
//The parameters are (x, y) so tile2.getWidth() tells the Graphics2D
//object to move to the right the same amount of pixels as the "tile2"
//image is wide. (E.g. if tile2 width == 16, then the Graphics2D will
//move it's cursor 16 pixels to the right.)
//For x, a positive number goes right, negative goes left.
//For y, a positive goes down, and a negative goes up.
g.translate(tile2.getWidth(), 0);
//Draw the second image.
g.drawImage(tile2, 0, 0, null);
//Close the Graphics2D object.
g.dispose();
//Optional, merely shows the finished product in a dialog.
JOptionPane.showMessageDialog(null, new ImageIcon(map));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment