Hello friends, It’s being long time that I’ve not shared anything but Today I am gonna share a Java Program by which you can split an Image to multiple images. It could be very useful when you want to make a puzzle game, or you can integrate it with your own idea. So here is the code.
Java Program to Split Image to Multiple Images
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * * @author Rajesh Kumar Sahanee */ public class SplitImage { public static BufferedImage[] getImages(Image img, int rows, int column) { BufferedImage[] splittedImages = new BufferedImage[rows * column]; BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics g = bi.createGraphics(); g.drawImage(img, 0, 0, null); int width = bi.getWidth(); int height = bi.getHeight(); int pos = 0; int swidth = width / column; int sheight = height / rows; for (int i = 0; i < rows; i++) { for (int j = 0; j < column; j++) { BufferedImage bimg = bi.getSubimage(j * swidth, i * sheight, swidth, sheight); splittedImages[pos] = bimg; pos++; } } return splittedImages; } public static void main(String args[]) throws IOException { if(args.length >= 3){ BufferedImage bi = ImageIO.read(new File(args[0])); int rcount = Integer.parseInt(args[1]); int ccount = Integer.parseInt(args[2]); Image img = bi.getScaledInstance(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB); BufferedImage[] imgs = SplitImage.getImages(img, rcount, ccount); for(int i=0; i < imgs.length; i++){ ImageIO.write(imgs[i], "jpg", new File("img"+i+".jpg")); } } else { System.out.println("Usage: image-file-path rows-count column-count"); } } } |
How To Run
java SplitImage testimage.jpg 4 3
here 4 is number of rows and 3 is number of columns in which image would be split.
Note: testimage.jpg file should at current location where your program is
Output
Thanks for stopping by
please share if you like it
Comments