@Override
public String waterMark(File image, String imageFileName, String uploadPath,
String realUploadPath) {
String logoFileName = "logo_" + imageFileName;
OutputStream os = null;
try {
Image img = ImageIO.read(image);
int imgWidth = img.getWidth(null);
int imgHeight = img.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(img, 0, 0, imgWidth, imgHeight, null);
g.setFont(new Font(FONT_NAME,FONT_STYLE,FONT_SIZE));
g.setColor(FONT_COLOR);
//设置透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
int width = FONT_SIZE*getTextLength(MARK_TEXT);
int height = FONT_SIZE;
int widthDiff = imgWidth-width;
int heightDiff = imgHeight-height;
int x = X;
int y = Y;
x = x>widthDiff ? widthDiff : x;
y = y>heightDiff ? heightDiff : y;
g.drawString(MARK_TEXT, x, y+FONT_SIZE);
g.dispose();
os = new FileOutputStream(realUploadPath+"/"+logoFileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(bufferedImage);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(os!=null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return uploadPath+"/"+logoFileName;
}
public int getTextLength(String text){
int length = text.length();
for (int i = 0; i < text.length(); i++) {
String s = String.valueOf(text.charAt(i));
if(s.getBytes().length>1){
length++;
}
}
length = length%2==0?length/2:length/2+1;
return length;
}