Java BufferedImage Transform copyAndTranslateSubimage(BufferedImage src, Rectangle bounds)

Here you can find the source of copyAndTranslateSubimage(BufferedImage src, Rectangle bounds)

Description

In contrast to BufferedImage.getSubimage, this method creates a copy of the data

License

Open Source License

Declaration

public static BufferedImage copyAndTranslateSubimage(BufferedImage src, Rectangle bounds) 

Method Source Code

//package com.java2s;
/*/*w  w w .j  a  v a 2 s  .  co  m*/
 * Copyright 2015 Laszlo Balazs-Csiki
 *
 * This file is part of Pixelitor. Pixelitor is free software: you
 * can redistribute it and/or modify it under the terms of the GNU
 * General Public License, version 3 as published by the Free
 * Software Foundation.
 *
 * Pixelitor is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Pixelitor. If not, see <http://www.gnu.org/licenses/>.
 */

import javax.swing.*;

import java.awt.Rectangle;

import java.awt.image.BufferedImage;

import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class Main {
    /**
     * In contrast to BufferedImage.getSubimage, this method creates a copy of the data
     */
    public static BufferedImage copyAndTranslateSubimage(BufferedImage src, Rectangle bounds) {
        assert src != null;
        assert bounds != null;

        //        Rectangle imageBounds = new Rectangle(0, 0, src.getWidth(), src.getHeight());
        //        Rectangle intersection = bounds.intersection(imageBounds);

        Rectangle intersection = SwingUtilities.computeIntersection(0, 0, src.getWidth(), src.getHeight(), // image bounds
                bounds);

        if (intersection.width <= 0 || intersection.height <= 0) {
            throw new IllegalStateException("empty intersection: bounds = " + bounds + ", src width = "
                    + src.getWidth() + ", src height = " + src.getHeight() + ", intersection = " + intersection);
        }

        Raster copyRaster = src.getData(intersection); // a copy
        Raster startingFrom00 = copyRaster.createChild(intersection.x, intersection.y, intersection.width,
                intersection.height, 0, 0, null);
        return new BufferedImage(src.getColorModel(), (WritableRaster) startingFrom00, src.isAlphaPremultiplied(),
                null);
    }
}

Related

  1. getTransformedImage(BufferedImage image, double scaleX, double scaleY, double shearX, double shearY)
  2. transform(BufferedImage image, int numquadrants)
  3. transform(BufferedImage image, int sx, int sy, int dx, int dy)
  4. transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight)