给图片添加水印

/**
* @param iconPath 水印图片路径
* @param sourceBytes 源文件字节流
* @param position 水印位置
* @param degree 便宜度
* @return
*/
public static byte[] markImageByIcon(String iconPath, byte[] sourceBytes, Integer position, Integer degree) {
byte[] targetByte = null;
ByteArrayOutputStream os = null;
try {
Image srcImg = ImageIO.read(new ByteArrayInputStream(sourceBytes));
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
// 1、得到画笔对象
Graphics2D g = buffImg.createGraphics();
// 2、设置对线段的锯齿状边缘处理
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0,
null);
// 3、设置水印旋转
if (null != degree) {
g.rotate(Math.toRadians(degree),
(double) buffImg.getWidth() / 2,
(double) buffImg.getHeight() / 2);
}
// 4、水印图片的路径 水印图片一般为gif或者png的,这样可设置透明度
ImageIcon imgIcon = new ImageIcon(iconPath);
// 5、得到Image对象。
Image img = imgIcon.getImage();

ImagePosition imagePosition;
if (null != position) {
imagePosition = getPosition(position, srcImg.getWidth(null), srcImg.getHeight(null),
img.getWidth(null), img.getHeight(null));
} else {
imagePosition = new ImagePosition(positionWidth, positionHeight);
}

g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
// 6、水印图片的位置
g.drawImage(img, imagePosition.getWidth(), imagePosition.getHeight(), null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// 7、释放资源
g.dispose();
// 8、生成图片
os = new ByteArrayOutputStream();
ImageIO.write(buffImg, "JPG", os);
targetByte = os.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != os) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return targetByte;
}
private static ImagePosition getPosition(int position, int width, int height, int icWidth, int icHeight) {
int x = 0;
int y = 0;
switch (position) {
case 1:
//位置 0,0
break;
case 2:
x = (width / 2) - (icWidth / 2);
break;
case 3:
x = width - icWidth;
break;
case 4:
y = (height / 2) - (icHeight / 2);
break;
case 5:
x = (width / 2) - (icWidth / 2);
y = (height / 2) - (icHeight / 2);
break;
case 6:
x = width - icWidth;
y = (height / 2) - (icHeight / 2);
break;
case 7:
y = height - icHeight;
break;
case 8:
x = (width / 2) - (icWidth / 2);
y = height - icHeight;
case 9:
x = width - icWidth;
y = height - icHeight;
break;
default:
}
return new ImagePosition(x, y);
}

posted on 2018-10-13 14:12  骑着乌龟漂流  阅读(492)  评论(0编辑  收藏  举报

导航