public class TxtToImage {
private int maxLineNum = 27; // 每行最大字数
private int maxlength = 800;
public File createImage(String strSrc, Font font, String fileName) {
if ((font.getSize() * maxLineNum) > maxlength) {
maxLineNum = maxlength / font.getSize();
}
int width = strSrc.length() < maxLineNum ? (strSrc.length() + 1)
* font.getSize() : font.getSize() * (maxLineNum + 1);
int height = (strSrc.length() / maxLineNum + 2) * font.getSize();
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setBackground(new Color(1.0f, 1.0f, 1.0f, 0.01f));
g.clearRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.setFont(font);
int x = 3, y = 3;
int count = strSrc.length();
int i = 0;
String getone = null;
while (count > 0) {
getone = strSrc.substring(i, i + 1);
if (i % maxLineNum == 0) {
y += font.getSize();
x = 10;
}
g.drawString(getone, x, y);
x += font.getSize();
i++;
count--;
}
g.dispose();
bi.flush();
FileOutputStream out = null;
try {
mkdirs(fileName);
out = new FileOutputStream(new File(fileName));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(param);
try {
encoder.encode(bi);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("ok..");
return new File(fileName);
}
private void mkdirs(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
File file2 = new File(fileName.substring(0,
fileName.lastIndexOf("\\")));
file2.mkdirs();
}
}
public static void main(String[] args) {
String str = "2014清明节放假安排:"
+ "中4月5日(星期六,农历清明当日)为法定节假日,又刚好星期六公休,所能调"
+ "到4月7日(星期一)补休。4月6日(星期日)公休。";
new TxtToImage().createImage(str, new Font("楷体", Font.PLAIN, 20),"d:\\image\\test.png");
}
}
java 字符串转image
最新推荐文章于 2023-04-25 11:44:36 发布