【问题标题】:Scaling and size-reducing image on a server在服务器上缩放和缩小图像
【发布时间】:2019-10-26 01:42:03
【问题描述】:

我需要缩小 JPG 图像,使其适合 1024x640 的矩形并保存,使其大小不超过 20 kB。通过一些谷歌搜索,我设法做到了这两点。对于我使用的缩放比例

private static BufferedImage scale(BufferedImage input, int width, int height) {
    final int type = input.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    final BufferedImage result = new BufferedImage(width, height, type);
    final Graphics2D g2 = result.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(input, 0, 0, width, height, null);
    g2.dispose();
    return result;
}

为了减小大小,我使用ImageWriterJPEGImageWriteParam 并以降低质量重复,直到文件大小低于限制。

它在我的机器上运行得相当好,但在测试服务器上,它做的事情很糟糕:

original file size:    174548
scaled down file size:  16995 - on my machine
                       228218 - on the server

所以缩小后的图片比原图大,画质很差。

我虽然可能与headless java problem有关,但java安装不是无头的(我从来没有得到HeadlessException):

java -version
openjdk version "1.8.0_222"
OpenJDK Runtime Environment (build 1.8.0_222-8u222-b10-1ubuntu1~16.04.1-b10)
OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode)

知道发生了什么吗?

【问题讨论】:

  • 问题可能是大量的元数据。我不了解 Java,但在命令行中,您可以使用 -strip 删除大部分(如果不是全部)元数据。同样在命令行中,有一个定义允许 Imagemagick 输出您想要的文件大小。请参阅 -define jpeg:extent={size} imagemagick.org/Usage/formats/#jpg_write

标签: java image-processing headless


【解决方案1】:

我们使用 ImageMagick 来调整图像大小和重新格式化。它可以给你灵活性。我们设法更早地使用它来满足与您类似的需求。

ImageMagick 利用多个计算线程来提高性能,并且可以读取、处理或写入兆、千兆或兆像素大小的图像。

它是免费的开源软件。更多细节可以参考官网:https://imagemagick.org/index.php

示例程序的工作原理如下:

ConvertCmd cmd = new ConvertCmd();

// create the operation, add images and operators/options
IMOperation op = new IMOperation();
op.addImage("source_picture.jpg"); // source file
op.resize(800,600);
// of op.resize(800); // and height calculate automatically
op.addImage("resized_picture.jpg"); // destination file file

// execute the operation
cmd.run(op);

查看stackoverflow相关线程Image magick java

希望对你有帮助!

【讨论】:

    【解决方案2】:

    问题是使用Graphics2D 完成的调整大小。不知道为什么它会这样做,但是在将其替换为java-image-scaling 之后,问题就消失了。

    很有可能那里有更好的库,但对于当前的需求,这个已经足够了。

    【讨论】:

    • java-image-scaling 自 2014 年以来已失效。我在 github.com/MarkJeronimus/ImageUtilities 进行了替换
    • @MarkJeronimus 谢谢,如果我需要重做它,我会研究它。现在,它已经足够好了。
    猜你喜欢
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多