Java无头双三次图像resize

我需要执行java图像裁剪并在没有X服务器的情况下resize。

我尝试了几种方法。 下面的第一个方法有效,但输出一个相当难看的resize的图像(可能使用最近邻居算法resize:

static BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) { int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType); Graphics2D g = scaledBI.createGraphics(); if (preserveAlpha) { g.setComposite(AlphaComposite.Src); } g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); g.dispose(); return scaledBI; } 

所以我决定使用bicubic resize,它可以提供更好的结果:

 public static BufferedImage createResizedCopy(BufferedImage source, int destWidth, int destHeight, Object interpolation) { if (source == null) throw new NullPointerException("source image is NULL!"); if (destWidth <= 0 && destHeight <= 0) throw new IllegalArgumentException("destination width & height are both <=0!"); int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); double xScale = ((double) destWidth) / (double) sourceWidth; double yScale = ((double) destHeight) / (double) sourceHeight; if (destWidth <= 0) { xScale = yScale; destWidth = (int) Math.rint(xScale * sourceWidth); } if (destHeight <= 0) { yScale = xScale; destHeight = (int) Math.rint(yScale * sourceHeight); } GraphicsConfiguration gc = getDefaultConfiguration(); BufferedImage result = gc.createCompatibleImage(destWidth, destHeight, source.getColorModel().getTransparency()); Graphics2D g2d = null; try { g2d = result.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation); AffineTransform at = AffineTransform.getScaleInstance(xScale, yScale); g2d.drawRenderedImage(source, at); } finally { if (g2d != null) g2d.dispose(); } return result; } public static GraphicsConfiguration getDefaultConfiguration() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); return gd.getDefaultConfiguration(); } 

这工作正常,直到我试图把它放在服务器上,此时我碰到了java.awt.HeadlessException。 我尝试使用java.awt.headless = true失败了。

所以,问题是:如何在没有X服务器的情况下使用双三次插值算法在Java中resize并裁剪和成像?

答:使用Bozho注释中的代码,我创建了这个function,它可以实现这一function(插值应该是RenderingHints.VALUE_INTERPOLATION_ *)。

 public static BufferedImage createResizedCopy(BufferedImage source, int destWidth, int destHeight, Object interpolation) { BufferedImage bicubic = new BufferedImage(destWidth, destHeight, source.getType()); Graphics2D bg = bicubic.createGraphics(); bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation); float sx = (float)destWidth / source.getWidth(); float sy = (float)destHeight / source.getHeight(); bg.scale(sx, sy); bg.drawImage(source, 0, 0, null); bg.dispose(); return bicubic; } 

检查此代码 。 还要检查Image.getScaledInstance(..) (“平滑”缩放)是否无法解决问题。 最后,看一下java-image-scaling-library 。