之前没有做过水印,领导说给照片添加水印的时候感觉好像不是多么好做,但是真的的做的时候发现这个功能真的不是多么难。
第一步
将你拍摄的照片或者选择的照片转为bitmap的格式 。
第二步
创建一个新的bitmap。这个就是你要添加的水印,可以是文字,可以是图片。
第三步
将两个bitmap进行一个合并。
部分代码
//第一步目的图转bitmap
bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(getPhotoHelper.getImageUri()));
//创建水印
public static Bitmap CreateWatermark(String mark, int w , int h, Context context)
{
//创建一个和原图一样的bitmap
Bitmap waterMark = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
// 创建画布
Canvas canvasTemp = new Canvas(waterMark);
Paint p = new Paint(); //画笔
String familyName = "宋体";
Typeface font = Typeface.create(familyName, Typeface.BOLD);
p.setColor(Color.WHITE);
p.setTypeface(font);
p.setAlpha(80);
p.setTextSize(80);
//根据自己的需求进行位置选的
canvasTemp.drawText(mark, x, y, p);
// 这里是我根据我的自己需求
/* canvasTemp.save();
canvasTemp.rotate(-30);
//获取要添加文字的宽度
float textWidth = p.measureText(mark);
int index = 0;
//行循环,从高度为0开始,向下每隔80dp开始绘制文字
for (int positionY = -DensityUtil.dp2px(context, 30); positionY <= h; positionY += DensityUtil.dp2px(context, 100)) {
//设置每行文字开始绘制的位置,0.58是根据角度算出tan30°,后面的(index++ % 2) * textWidth是为了展示效果交错绘制
float fromX = -0.58f * h + (index++ % 2) * textWidth;
//列循环,从每行的开始位置开始,向右每隔2倍宽度的距离开始绘制(文字间距1倍宽度)
for (float positionX = fromX; positionX < w; positionX += textWidth * 2) {
//绘制文字
canvasTemp.drawText(mark, positionX, positionY, p);
}
}*/
return waterMark;
}
//合并
/**
src 原图
waterBitmap 水印图
**/
public static Bitmap CreateBitmapWithWatermark(Bitmap src, Bitmap watermark)
{
if (src == null)
{
return null;
}
int w = src.getWidth();
int h = src.getHeight();
int ww = watermark.getWidth();
int wh = watermark.getHeight();
Bitmap destMap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
Canvas cv = new Canvas(destMap);
cv.drawBitmap(src, 0, 0, null);// 在 0,0坐标开始画入src
//这里的0 0 代指的X Y坐标点
cv.drawBitmap(watermark, 0 ,0, null);// 在 0,0坐标开始画入watermark
cv.save(Canvas.ALL_SAVE_FLAG);// 保存
cv.restore();// 存储
return destMap;
}