【发布时间】:2019-10-01 14:37:58
【问题描述】:
我必须将 Java 中的图像大小从大约 1000px 调整为 200px ,然后将它们复制到 web 文件夹中,以便以 200px 的分辨率显示在 Html 报告中。 (注意我必须创建这些文件,因为原始图像将无法用于网络服务器,并且仅复制原始图像将需要太多空间。)
虽然原始图像通常质量很高,但 200 像素的图像可能会很粗糙,我可以调整下面的代码以生成更高质量的图像
public static BufferedImage resizeUsingImageIO(Image srcImage, int size)
{
int w = srcImage.getWidth(null);
int h = srcImage.getHeight(null);
// Determine the scaling required to get desired result.
float scaleW = (float) size / (float) w;
float scaleH = (float) size / (float) h;
MainWindow.logger.finest("Image Resizing to size:" + size + " w:" + w + ":h:" + h + ":scaleW:" + scaleW + ":scaleH" + scaleH);
//Create an image buffer in which to paint on, create as an opaque Rgb type image, it doesn't matter what type
//the original image is we want to convert to the best type for displaying on screen regardless
BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
// Set the scale.
AffineTransform tx = new AffineTransform();
tx.scale(scaleW, scaleH);
// Paint image.
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, size, size);
g2d.setComposite(AlphaComposite.SrcOver);
g2d.drawImage(srcImage, tx, null);
g2d.dispose();
return bi;
【问题讨论】:
-
是否反对将此作为stackoverflow.com/questions/24745147/… 的副本关闭?
-
另一个问题给出了很多理论上的答案,但没有给出实际做什么的简单答案,这个似乎
-
我对链接问题stackoverflow.com/a/24746194/3182664 的回答显示了minimal reproducible example,其中包含调整图像大小并将其存储为任意质量的JPG 格式的方法。它可以被认为是一个纯效用函数。我还比较了 stackoverflow.com/a/32278737/3182664 中不同缩放方法的性能,以及可以轻松重复使用的不同
scaleWith...方法。
标签: java bufferedimage java-2d