java 给图片添加文字
最近开发中要实现给图片加文字功能,本打算用Jmagick实现的,可是中文出现乱码,没有找到解决办法,就用
最原始的方法实现了,如果随知道Jmagick图片解决中文乱码问题,可以告诉我,谢谢!!!
public class d {
public static void main(String [] a){
d.createMark("e8.jpg","e81.jpg","",null, 1,"",100);
//System.out.println(d.createMark("e8.jpg","e81.jpg","",null, 1,"",16));
}
public static boolean createMark(String filePath,String filePath1, String markContent,
Color markContentColor, float qualNum, String fontType, int fontSize) {
markContentColor = Color.gray;
ImageIcon imgIcon = new ImageIcon(filePath);
Image theImg = imgIcon.getImage();
//Image可以获得 输入图片的信息
int width = theImg.getWidth(null);
int height = theImg.getHeight(null);
//800 800 为画出图片的大小
BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
//2d 画笔
Graphics2D g = bimage.createGraphics();
g.setColor(markContentColor);
g.setBackground(Color.white);
//画出图片-----------------------------------
g.drawImage(theImg, 0, 0, null);
//画出图片-----------------------------------
//--------对要显示的文字进行处理--------------
markContent = "孙留成是好人 www.sego.com";// 文字
AttributedString ats = new AttributedString(markContent);
Font f = new Font(fontType, Font.BOLD, fontSize);
ats.addAttribute(TextAttribute.FONT, f, 0, markContent.length());
AttributedCharacterIterator iter = ats.getIterator();
//----------------------
g.drawString(iter, (int) (width - width+10), (int) (height - height/2));
//添加水印的文字和设置水印文字出现的内容 ----位置
g.dispose();//画笔结束
try {
//输出 文件 到指定的路径
FileOutputStream out = new FileOutputStream(filePath1);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(qualNum, true);
encoder.encode(bimage, param);
out.close();
} catch (Exception e) {
return false;
}
return true;
}
}