Java BufferedImage Split splitByWidth(BufferedImage img, int width)

Here you can find the source of splitByWidth(BufferedImage img, int width)

Description

Split the image into equally sized sub-images.

License

LGPL

Parameter

Parameter Description
img the image to split
width the split width in pixels

Return

the array of images

Declaration

public static BufferedImage[] splitByWidth(BufferedImage img, int width) 

Method Source Code


//package com.java2s;
/*/*from  w  w  w.jav  a  2s.  co m*/
 * Copyright 2008-2014, David Karnok 
 * The file is part of the Open Imperium Galactica project.
 * 
 * The code should be distributed under the LGPL license.
 * See http://www.gnu.org/licenses/lgpl.html for details.
 */

import java.awt.image.BufferedImage;

public class Main {
    /**
     * Split the image into equally sized sub-images.
     * @param img the image to split
     * @param width the split width in pixels
     * @return the array of images
     */
    public static BufferedImage[] splitByWidth(BufferedImage img, int width) {
        if (img.getWidth() > 0) {
            BufferedImage[] result = new BufferedImage[(img.getWidth() + width - 1) / width];
            int x = 0;
            for (int i = 0; i < result.length; i++) {
                int x2 = Math.min(x + width - 1, img.getWidth() - 1);
                result[i] = newSubimage(img, x, 0, x2 - x + 1, img.getHeight());
                x += width;
            }
            return result;
        }
        return new BufferedImage[0];
    }

    /**
     * Returns an independent subimage of the given main image. copying data from the original image.
     * @param src the source image.
     * @param x the x coordinate
     * @param y the y coordinate
     * @param w the width
     * @param h the height
     * @return the extracted sub-image
     */
    public static BufferedImage newSubimage(BufferedImage src, int x, int y, int w, int h) {
        BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        int[] tmp = new int[w * h];
        src.getRGB(x, y, w, h, tmp, 0, w);
        bimg.setRGB(0, 0, w, h, tmp, 0, w);
        return bimg;
    }
}

Related

  1. split(int w, int h, BufferedImage src)
  2. splitImage(BufferedImage image, int row, int col)
  3. splitImage(BufferedImage image, int rows, int cols)
  4. splitImage(BufferedImage img, int cols, int rows)
  5. splitImage(BufferedImage img, int rows, int cols)