Here you can find the source of fitToSize(BufferedImage source, int targetWidth, int targetHeight)
Parameter | Description |
---|---|
source | Source image. |
targetWidth | Width in pixel. |
targetHeight | Height in pixel. |
public static BufferedImage fitToSize(BufferedImage source, int targetWidth, int targetHeight)
//package com.java2s; //License from project: Apache License import java.awt.Graphics2D; import java.awt.image.BufferedImage; public class Main { /**//from w w w . ja v a 2s . co m * Scale the image with original aspect ratio, then cut to fit the target * size if necessary. * * @param source * Source image. * @param targetWidth * Width in pixel. * @param targetHeight * Height in pixel. * @return The image with exactly the size. */ public static BufferedImage fitToSize(BufferedImage source, int targetWidth, int targetHeight) { int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); if (sourceWidth == targetWidth && sourceHeight == targetHeight) { return source; } // scale: int sx1 = 0; int sy1 = 0; int sx2 = sourceWidth; int sy2 = sourceHeight; if (sourceWidth * targetHeight < sourceHeight * targetWidth) { // cut height: int newHeight = (int) ((float) sourceWidth * targetHeight / targetWidth); sy1 = (sourceHeight - newHeight) / 2; sy2 = sy1 + newHeight; } else if (sourceWidth * targetHeight > sourceHeight * targetWidth) { // cut width: int newWidth = (int) ((float) sourceHeight * targetWidth / targetHeight); sx1 = (sourceWidth - newWidth) / 2; sx2 = sx1 + newWidth; } BufferedImage target = new BufferedImage(targetWidth, targetHeight, source.getType()); Graphics2D g = target.createGraphics(); g.drawImage(source, 0, 0, targetWidth, targetHeight, sx1, sy1, sx2, sy2, null); g.dispose(); return target; } }