【发布时间】:2012-02-17 01:27:03
【问题描述】:
I am using JLabel 从字符串创建图像文件。
我必须指定图像尺寸 (label.setSize(width, height)),否则会出现异常:
java.lang.IllegalArgumentException: Width (0) and height (0) cannot be <= 0
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1016)
at java.awt.image.BufferedImage.<init>(BufferedImage.java:338)
at com.shopsnips.portal.services.ImageCreator.createFromText(ImageCreator.java:31)
at com.shopsnips.portal.services.ImageCreator.main(ImageCreator.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
我可以使用控制字体大小
label.setFont(new Font("Serif", Font.BOLD, 26));
当我使用太大而无法容纳固定尺寸的字体或文本时,标签会被截断,而包含“...”。有没有办法确定仍然适合我设置的尺寸的最佳/最大字体大小?
或者,如何确定当前设置(字体大小+尺寸)是否会导致文本被截断?
这里有一些来源:
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 ImageCreator {
private ImageCreator(){}
private final static String FONT = "Freestyle Script";
public static void main(String[] args) {
Path outputFile = Paths.get("c:\\tmp\\img\\test.png");
createFromText("Hello World - this is a long text", outputFile, 150, 50);
}
/**
* <p>Create an image from text. <p/>
* <p/>
* https://stackoverflow.com/a/4437998/11236
*/
public static void createFromText(String text, Path outputFile, int width, int height) {
JLabel label = new JLabel(text, SwingConstants.CENTER);
label.setSize(width, height);
label.setFont(new Font(FONT, Font.BOLD, 24));
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);
}
}
}
请登录后发表评论。
【问题讨论】: