Question:
Despite adhering to the JavaDocs, attempts to scale a BufferedImage using Graphics2D have proven futile. The following code is used:
BufferedImage image = MatrixToImageWriter.getBufferedImage(encoded); Graphics2D grph = image.createGraphics(); grph.scale(2.0, 2.0); grph.dispose();
Answer:
The issue may arise from using Graphics2D alone, which only scales the on-screen rendering without altering the actual image data. For effective image rescaling, AffineTransformOp is recommended, as it provides additional control over the interpolation type. Here's how the code can be modified using AffineTransformOp:
BufferedImage before = getBufferedImage(encoded); int w = before.getWidth(); int h = before.getHeight(); BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); AffineTransform at = new AffineTransform(); at.scale(2.0, 2.0); AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); after = scaleOp.filter(before, after);
This approach allows for bilinear interpolation, which produces smooth and accurate rescaling results.
The above is the detailed content of Why Doesn't Graphics2D Effectively Rescale a BufferedImage?. For more information, please follow other related articles on the PHP Chinese website!