java 图片上写入文字

以下方法在fc6下测试通过,假设用户的jre路径为 /usr/java/jdk1.6.0_03/jre/
#cd /usr/java/jdk1.6.0_03/jre/lib/fonts
#sudo mkdir fallback
将C:\WINDOWS\Fonts\simsun.ttc拷贝到 /usr/java/jdk1.6.0_03/jre/lib/fonts/fallback文件夹内 ok!

		//读取图片文件,得到BufferedImage对象
		BufferedImage bimg=ImageIO.read(new FileInputStream("c:/u1.jpg"));
		//得到Graphics2D 对象
		Graphics2D g2d=(Graphics2D)bimg.getGraphics();
		//设置颜色和画笔粗细
		g2d.setColor(Color.RED);
		g2d.setStroke(new BasicStroke(5));
		g2d.setFont(new Font("Serif", Font.PLAIN, 13));
		//绘制图案或文字
		g2d.drawString("陈克永", 174, 257);
		g2d.drawString("2015", 279, 257);
		g2d.drawString("8", 343, 257);

		//保存新图片
		ImageIO.write(bimg, "JPG",new FileOutputStream("c:/u2.jpg"));	


public String lpzjImg(){
		this.getResponse().setContentType("image/jpeg;charset=UTF-8");
		this.getResponse().setHeader("Content-Disposition", "attachment;filename=lpzj.jpg");
		try{
			//读取图片文件,得到BufferedImage对象
			BufferedImage bimg=ImageIO.read(new FileInputStream(FileAction.class.getClassLoader().getResource("/").getPath()+"other/lpzjjz.jpg"));
			//得到Graphics2D 对象
			Graphics2D g2d=(Graphics2D)bimg.getGraphics();
			//设置颜色和画笔粗细
			g2d.setColor(Color.RED);
			g2d.setStroke(new BasicStroke(5));
			g2d.setFont(new Font("Serif", Font.PLAIN, 13));
			//绘制图案或文字
			Object tupfullname = xhjConsoleDao.getBaseSession().createSQLQuery("select fullname from tbl_user_profile  where id="+userProfileName).uniqueResult();
			g2d.drawString(tupfullname.toString(), 174, 257);
			g2d.drawString(lpzjYearMonth.substring(0, 4), 279, 257);
			g2d.drawString(lpzjYearMonth.substring(4), 343, 257);
			//保存新图片
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			ImageIO.write(bimg, "JPG",outputStream);	
			outputStream.flush();
	        
			byte[] byteArray = outputStream.toByteArray();
			getResponse().getOutputStream().write(byteArray);
		}catch(Exception e){
			//ignore
		}
		return null;
	}

你可能感兴趣的:(java)