convert And Scale BufferedImage - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Scale

Description

convert And Scale BufferedImage

Demo Code

/*/* ww  w .j  a  va2  s.c  o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import java.awt.image.RenderedImage;

public class Main {
    private static BufferedImage convertAndScaleImage(
            final RenderedImage img, final Dimension targetDimension,
            final int imageType) {
        Dimension bmpDimension = targetDimension;
        if (bmpDimension == null) {
            bmpDimension = new Dimension(img.getWidth(), img.getHeight());
        }
        final BufferedImage target = new BufferedImage(bmpDimension.width,
                bmpDimension.height, imageType);
        transferImage(img, target);
        return target;
    }

    private static void transferImage(final RenderedImage source,
            final BufferedImage target) {
        final Graphics2D g2d = target.createGraphics();
        try {
            g2d.setBackground(Color.white);
            g2d.setColor(Color.black);
            g2d.clearRect(0, 0, target.getWidth(), target.getHeight());

            final AffineTransform at = new AffineTransform();
            if (source.getWidth() != target.getWidth()
                    || source.getHeight() != target.getHeight()) {
                final double sx = target.getWidth()
                        / (double) source.getWidth();
                final double sy = target.getHeight()
                        / (double) source.getHeight();
                at.scale(sx, sy);
            }
            g2d.drawRenderedImage(source, at);
        } finally {
            g2d.dispose();
        }
    }
}

Related Tutorials