I have created some code in Java that slices up an image into rows and columns and then saves each image to the file system. This works but there are some improvements I would like to make
I would like it to automatically know the original file name and extension using the StringTokenizer class so I do not have to hard code them into the class.
for example...
I want the filenames to be
targetFolder+"/"+originalfilename+"-"+(count++)"."+extension
Any general comments on the code would be appreciated too because there may be a better way of doing this
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class GridImage implements Runnable {
private BufferedImage image;
private int rows, columns;
private BufferedImage[][] smallImages;
private int smallWidth;
private int smallHeight;
public GridImage(String filename, int rows, int columns) {
this.rows = rows;
this.columns = columns;
try {
image = ImageIO.read(new File(filename));
} catch (IOException e) {
e.printStackTrace();
}
this.smallWidth = image.getWidth() / columns;
this.smallHeight = image.getHeight() / rows;
smallImages = new BufferedImage[columns][rows];
}
public void run() {
int count = 0;
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
smallImages[x][y] = image.getSubimage(x * smallWidth, y
* smallHeight, smallWidth, smallHeight);
try {
ImageIO.write(smallImages[x][y], "png", new File("tile-"
+ (count++) + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
GridImage image = new GridImage("img/card-grid-image-mass-effect.jpg",
4, 15);
new Thread(image).start();
}
}
This code actually produces the smaller images with a different filetype from the original
What's the best way to slice up an image into a two dimentional array of tiles and save them to the bloody laptop?
getFileName( ... )
method. – abuzittin gillifirca Jan 15 at 7:44