/**创建文字水印
* @param filePath 源文件路径
* toImg 生成文件位置
* text 水印文本
* pos logo在源图片中的相对位置,以像素点为单位
* pointSize 用于设置点阵大小
* @return
* @throw MagickException
* @author sulliy@sina.com 2010-8-11
*/
public static void createWaterPrintByText(String filePath, String toImg, String text
, Point pos, int pointSize)
throws MagickException {
if (!checkType(filePath) || !checkType(toImg)) {
return;
}
if (null == text || "".equals(text)) {
text = "sulliy@sina.com";
}
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);
Dimension imageDim = aImage.getDimension();
int width = imageDim.width;
int height = imageDim.height;
if (width <= (int)pos.getX() || height <= (int)pos.getY()) {
pos.setLocation(0, 0);
}
int a = 0;
int b = 0;
String[] as = text.split("");
for (String string : as) {
if (string.matches("[\u4E00-\u9FA5]")) {
a++;
}
if (string.matches("[a-zA-Z0-9]")) {
b++;
}
}
int tl = a * 12 + b * 6 ;//字符长度
MagickImage scaled = aImage.scaleImage(width, height);
if (width > tl && height > 5) {
DrawInfo aInfo = new DrawInfo(info);
aInfo.setFill(PixelPacket.queryColorDatabase("white"));
aInfo.setUnderColor(new PixelPacket(65535, 65535, 65535, 65535));//设置为透明颜色
aInfo.setPointsize(pointSize);
// 解决中文乱码问题,自己可以去随意定义个自己喜欢字体,我在这用的微软雅黑
String fontPath = "C:/WINDOWS/Fonts/MSIMHEI.TTF";
// String fontPath = "/usr/maindata/MSYH.TTF";
aInfo.setFont(fontPath);
aInfo.setTextAntialias(true);
aInfo.setOpacity(0);//透明度
aInfo.setText(text);
aInfo.setGeometry("+" + ((int)pos.getX() + "+" + (int)pos.getY()));
scaled.annotateImage(aInfo);
}
scaled.setFileName(toImg);
scaled.writeImage(info);
scaled.destroyImages();
}
/**切取图片
* @param imgPath 原图路径
* toPath 生成文件位置
* w 左上位置横坐标
* h 左上位置竖坐标
* x 右下位置横坐标
* y 右下位置竖坐标
* @return
* @throw MagickException
* @author sulliy@sina.com 2010-8-11
*/
public static void cutImg(String imgPath, String toPath, int w, int h,
int x, int y) throws MagickException {
ImageInfo infoS = null;
MagickImage image = null;
MagickImage cropped = null;
Rectangle rect = null;
try {
infoS = new ImageInfo(imgPath);
image = new MagickImage(infoS);
rect = new Rectangle(x, y, w, h);
cropped = image.cropImage(rect);
cropped.setFileName(toPath);
cropped.writeImage(infoS);