【发布时间】:2012-03-22 05:36:16
【问题描述】:
我在 Windows 和 Linux 上使用 javax.imageio 从文本字符串生成图像,我发现图像的质量非常不同(Linux = 质量差,物理尺寸小,尽管尺寸相同)。
Linux (Ubunutu),443 字节
Windows 7,1,242 字节
我使用相同的字体文件(从 Windows 上传到 linux),并使用此代码生成图像。知道如何提高 linux 生成的图像的质量吗?首先为什么生成的图像不同?
我已尝试设置 explicit compression(通过 iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);),但尝试设置时出现 UnsupportedOperationException。
更新:
这是一个 SSCCE。我已经更新了我的示例并删除了字体,结果是一致的。如果您在两个系统上都设置了字体,它们也会发生。
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Example {
/**
* <p>Create an image from text. <p/>
* <p/>
* http://stackoverflow.com/a/4437998/11236
*/
public static void createFromText(String text, Path outputFile, int width, int height, Color color, int fontSize) {
JLabel label = new JLabel(text, SwingConstants.CENTER);
label.setSize(width, height);
label.setForeground(color);
BufferedImage image = new BufferedImage(
label.getWidth(), label.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics g = null;
try {
// paint the html to an image
g = image.getGraphics();
g.setColor(Color.BLACK);
label.paint(g);
} finally {
if (g != null) {
g.dispose();
}
}
// get the byte array of the image (as jpeg)
try {
ImageIO.write(image, "png", outputFile.toFile());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
Path output = Paths.get("/tmp/foo.png");
createFromText("Custom Text", output, 200, 40, Color.blue, 30);
}
}
【问题讨论】:
-
“我试过了..” 尝试发布SSCCE。但我建议您排除
JLabel,而是使用RenderingHints映射直接将字符串绘制到图形实例,您可以在其中指定..可以指定的所有内容。后者将绕过一些可能使用的不同默认值。 -
另外,您似乎认为不同之处在于图像的保存方式。我(和其他人,显然)怀疑是这种情况。在渲染之前将
JLabel本身弹出到JOptionPane中是值得的。抓取屏幕截图并将其与其他系统的屏幕截图进行比较。最初的JLabel实例看起来是否相同? -
@AndrewThompson - 我可能确实需要制作一个 sccee。我会检查 RenderingHints。我无法在 linux 系统上轻松预览图像,我认为它没有安装 UI……它是一个 EC2 ubuntu 服务器。
-
@AndrewThompson - 更新为真正的 SSCCE。
-
好吧,我设置了我能找到的所有渲染提示(更新了 SSCCE gist.github.com/1973391),图像更接近了,但仍然不完全相同。我还注意到我使用的字体没有 BOLD 版本,只有 PLAIN 版本。当我修改代码以输出 PLAIN 版本时,图像现在看起来几乎完全相同......仍然不是二进制相同。
标签: java image javax.imageio