我需要执行java图像裁剪并在没有X服务器的情况下调整大小。
我尝试了几种方法。 下面的第一个方法有效,但输出一个相当难看的调整大小的图像(可能使用最近邻居算法调整大小:
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中调整大小并裁剪和成像?
答案: 使用Bozho注释中的代码,我创建了这个函数,它可以解决这个问题(插值应该是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;
}
答案 0 :(得分:3)
检查this code。同时检查Image.getScaledInstance(..)
(“平滑”缩放)是否无法解决问题。最后,看看java-image-scaling-library。