#5, First Floor, 4th Street , Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

How to split an image in java?

Description

This code describes to split the image into set of image chunks and the image split is stored in current directory. Generated images can be used for the application such as Image based authentication schemes.

Sample Code
  • Filename: TestImageSplit .java

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.awt.*;
import javax.swing.*;

public class TestImageSplit {
static String inputFile;
static String filename;

public static void main(String[] args) throws IOException {

JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

if (fc.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) {
inputFile=fc.getSelectedFile().getPath();
filename=fc.getSelectedFile().getName();
}

File file = new File(inputFile); // path of selecetd image
FileInputStream fis = new FileInputStream(file);
BufferedImage image = ImageIO.read(fis); //reading the image file

int rows = 4; //You should decide the values for rows and cols variables
int cols = 4;
int chunks = rows * cols;

int chunkWidth = image.getWidth() / cols; // determines the chunk width and height
int chunkHeight = image.getHeight() / rows;
int count = 0;
BufferedImage imgs[] = new BufferedImage[chunks]; //Image array to hold image chunks
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
//Initialize the image array with image chunks
imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

// draws the image chunk
Graphics2D gr = imgs[count++].createGraphics();
gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
gr.dispose();
}
}
System.out.println("Splitting done");

//writing mini images into image files
for (int i = 0; i < imgs.length; i++) {
ImageIO.write(imgs[i], "jpg", new File("img" + i + ".jpg"));
}
System.out.println("Mini images created");
}
}


Screenshots