本文共 1976 字,大约阅读时间需要 6 分钟。
代码很简单,没有什么新意!就是利用JDK做的简单绘图和变换!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | package com.oracle.day16; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * *@author huyongjian Oracle(Compus Solution Group) * @Date 2013-8-16 * @version 2.0 * @since JDK1.6(建议) Copy Right Information COMPUS SOLUTION GROUP IDE:Eclipse class: 打印生成jpg图片生成文字水印 JDK2D02 */ public class TestJdk2D02 { public String create(String str,String filePath, int width, int height){ String fileName=System.currentTimeMillis()+ ".jpg" ; String path=filePath+ "/" +fileName; File file= new File(path); BufferedImage bi= new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB); Graphics2D g2=(Graphics2D) bi.getGraphics(); g2.setColor.WHITE); g2.clearRect( 0 , 0 , width, height); Font font= new Font( "黑体" ,Font.BOLD, 25 ); g2.setFont(font); g2.setPaint(Color.RED); FontRenderContext context=g2.getFontRenderContext(); Rectangle2D bounds=font.getStringBounds(str, context); double x=(width-bounds.getWidth())/ 2 ; double y=(height-bounds.getHeight())/ 2 ; double ascent=-bounds.getY(); double baseY=y+ascent; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.drawString(str, ( int )x, ( int )baseY); try { ImageIO.write(bi, "jpg" , file); } catch (IOException e) { e.printStackTrace(); } return file.getPath(); } public static void main(String[] args) { TestJdk2D02 t= new TestJdk2D02(); System.out.println(t.create( "小夜的传说" , "c:/" , 500 , 38 )); } } |
运行之后在您的C盘中可以查看生成图片的水印!
群号:1936625305 Java程序员联盟 欢迎大家的加入!