Skip to content

Instantly share code, notes, and snippets.

@madan712
Created September 8, 2012 07:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save madan712/3672616 to your computer and use it in GitHub Desktop.
Save madan712/3672616 to your computer and use it in GitHub Desktop.
Java program to cut an image into number of pieces for a Jigsaw puzzle
/* JigsawImage.java
* @author: Madan Chaudhary
* @blog: javaxp.com
* */
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class JigsawImage {
public static void main(String[] args) {
try {
//Provide number of rows and column
int row = 4;
int col = 3;
BufferedImage originalImgage = ImageIO.read(new File("C:/temp/TajMahal.jpg"));
//total width and total height of an image
int tWidth = originalImgage.getWidth();
int tHeight = originalImgage.getHeight();
System.out.println("Image Dimension: " + tWidth + "x" + tHeight);
//width and height of each piece
int eWidth = tWidth / col;
int eHeight = tHeight / row;
int x = 0;
int y = 0;
for (int i = 0; i < row; i++) {
y = 0;
for (int j = 0; j < col; j++) {
try {
System.out.println("creating piece: "+i+" "+j);
BufferedImage SubImgage = originalImgage.getSubimage(y, x, eWidth, eHeight);
File outputfile = new File("C:/temp/TajMahal"+i+j+".jpg");
ImageIO.write(SubImgage, "jpg", outputfile);
y += eWidth;
} catch (Exception e) {
e.printStackTrace();
}
}
x += eHeight;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@mlarrubia
Copy link

Hey How do I print out the pieces?

@jredfox
Copy link

jredfox commented Jan 25, 2018

your code was flawed and x was named y and y was named x. your thing only works for one row

@kitesvishnu
Copy link

please add the code for merging the splitted images

@tavog96
Copy link

tavog96 commented Apr 16, 2018

Best code ever... great memes!!!! thanks :v

tajmahal00
tajmahal01
tajmahal10
tajmahal11

@pipen1976
Copy link

Amazing. It got some time to find you man. You are awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment