Java BufferedImage Split splitImage(BufferedImage image, int rows, int cols)

Here you can find the source of splitImage(BufferedImage image, int rows, int cols)

Description

split Image

License

Open Source License

Declaration

public static BufferedImage[] splitImage(BufferedImage image, int rows, int cols) throws Exception 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015, Daniel Ludin//from www  .j  a  v a 2 s . c  om
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Daniel Ludin (ludin@hispeed.ch) - initial implementation
 *******************************************************************************/

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import java.io.File;

import javax.imageio.ImageIO;

public class Main {
    public static BufferedImage[] splitImage(BufferedImage image, int rows, int cols) throws Exception {

        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

                int imageType = image.getType();
                if (imageType == 0) {
                    imageType = 5;
                }

                imgs[count] = new BufferedImage(chunkWidth, chunkHeight, imageType);

                // 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();
            }
        }

        //writing mini images into image files
        for (int i = 0; i < imgs.length; i++) {
            ImageIO.write(imgs[i], "jpg", new File("D:\\tmp", "img" + i + ".jpg"));
        }

        return imgs;

    }
}

Related

  1. split(int w, int h, BufferedImage src)
  2. splitByWidth(BufferedImage img, int width)
  3. splitImage(BufferedImage image, int row, int col)
  4. splitImage(BufferedImage img, int cols, int rows)
  5. splitImage(BufferedImage img, int rows, int cols)
  6. splitImage(final Image img, final int rows, final int cols)
  7. splitImage2D(BufferedImage img, int cols, int rows)