Java examples for 2D Graphics:BufferedImage Scale
Converts an image to a grayscale (8 bits) image.
/*//from w w w .java 2 s. c om * 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 { /** * Converts an image to a grayscale (8 bits) image. Optionally, the image * can be scaled. * * @param img * the image to be converted * @param targetDimension * the new target dimensions or null if no scaling is necessary * @return the grayscale image */ public static BufferedImage convertToGrayscale(final RenderedImage img, final Dimension targetDimension) { return convertAndScaleImage(img, targetDimension, BufferedImage.TYPE_BYTE_GRAY); } 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(); } } }