java 字符串转image

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");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值