使用JMagick给图片加文字水印的中文问题全解决java程序
ImageMagick (TM) 是一个免费的创建、编辑、合成图片的软件。它可以读取、转换、写入多种格式的图片。图片切割、颜色替换、各种效果的应用,图片的旋转、组合,文本,直线, 多边形,椭圆,曲线,附加到图片伸展旋转。ImageMagick是免费软件:全部源码开放,可以自由使用,复制,修改,发布。它遵守GPL许可协议。它 可以运行于大多数的操作系统。ImageMagick的大多数功能的使用都来源于命令行工具。
ImageMagick API的Java版实现JMagick也是一个非常好用的图片处理工具。在Windows和Linux平台下均可以使用。
在使用JMagick 的过程中,一般会遇到以下中文问题:无法使用中文给图片加文字水印。
在Linux下解决此 JMagick给图片加文字水印的中文问题的Java程序例如下。
/**
*
* @param filePath
* @param text
* @param opacity 透明度 0 - 100, 0 为不透明
* @return
*/
public static String addTextToPicture(String filePath, String text,
int opacity) {
System.setProperty(”jmagick.systemclassloader”, “no”);
int idx = filePath.indexOf(’.');
String newFileName = filePath.substring(0, idx) + “_twm” + filePath.substring(idx);
try {
ImageInfo info = new ImageInfo(filePath);
if (filePath.toUpperCase().endsWith(”JPG”) || filePath.toUpperCase().endsWith(”JPEG”)) {
info.setCompression(CompressionType.JPEGCompression); //压缩类别为JPEG格式
info.setPreviewType(PreviewType.JPEGPreview); //预览格式为JPEG格式
info.setQuality(95);
}
MagickImage aImage = new MagickImage(info);
DrawInfo aInfo = new DrawInfo(info);
aInfo.setFill(PixelPacket.queryColorDatabase(”green”));
aInfo.setUnderColor(PixelPacket.queryColorDatabase(”yellow”));
aInfo.setOpacity(0);
aInfo.setPointsize(20);
//aInfo.setFont(”Arial”); // 英文使用此字体也可
//注意这里解决中文字体问题,有以下两行才可正常显示
aInfo.setFont(fontPath);
String fontPath = "/home/user1/wmfont/simsun.ttf";
aInfo.setTextAntialias(true);
//Step 3: Writing The Text
aInfo.setText(text);
aInfo.setGeometry(”+40+60″);
/*
if(width > height){
aInfo.setGeometry(”+” +(480-140)+”+”+(int)((480/p)-10)); // 加文字水印在图象上的位置
}
else{
aInfo.setGeometry(”+”+(int)((480*p)-140)+”+” +(480-10)); //加文字水印在图象上的位置
}
*/
//Step 4: Annotating
aImage.annotateImage(aInfo);
//Step 5: Writing the new file
aImage.setFileName(newFileName);
aImage.writeImage(info);
aImage.destroyImages();
aImage = null;
} catch (MagickException e) {
}
return newFileName;
}
使用此程序,可以使用java程序在图片中加入网站地址,或者自己的签名等版权信息了。