之前写过一篇文章,给图片增加水印,不过那个是增加纯文本水印,今天介绍的是以图片叠加的那个是来增加水印。
国际惯例,上代码:
private String getWaterMask(String pic) {Bitmap bitmap = ImageUtil.fileInputStream(pic);int degree = ImageLoadUtil.readPictureDegree(pic);if (bitmap != null) {String content = "时 间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"\n\n区域位置:"+StringUtils.getTextNotNull(getIntentProcessName());View inflate = View.inflate(getActivity(), R.layout.view_water_mark, null);TextView tv_title=inflate.findViewById(com.haocang.base.R.id.tv_title);TextView tv_content=inflate.findViewById(com.haocang.base.R.id.tv_content);tv_title.setText(StringUtils.getTextString(getIntentOrgName()));tv_content.setText(content);Bitmap map = ImageLoadUtil.addTextWatermarkNew(bitmap, inflate, 100, bitmap.getHeight(), true, content, degree);File file = FileUtils.saveBitmapFile(map);return file.getPath();}return pic; //如果异常返回原图片}public static Bitmap addTextWatermarkNew(Bitmap src, View markerView, float x, float y, boolean recycle, String text, int rotateDegree) {Objects.requireNonNull(src, "src is null");Bitmap ret = null;if (rotateDegree == 0) {ret = src.copy(src.getConfig(), true);} else {Matrix matrix = new Matrix();matrix.postRotate(rotateDegree);ret = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);}Bitmap marker=viewToBitMap(markerView);Canvas canvas = new Canvas(ret);canvas.translate(x, y-markerView.getHeight()-100);canvas.drawBitmap(marker,0,0,null);
// canvas.drawBitmap(bitmap, 0, 0, null);//绘制小图片使用的代码if (recycle && !src.isRecycled()) src.recycle();return ret;}public static Bitmap viewToBitMap(@NonNull View view) {int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);view.measure(measureSpec, measureSpec);//由于是生成的,未进行测量,所有需要进行measure操作int measuredWidth = view.getMeasuredWidth();int measuredHeight = view.getMeasuredHeight();view.layout(0, 0, measuredWidth, measuredHeight);Bitmap bitmap = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888);bitmap.eraseColor(Color.TRANSPARENT);Canvas canvas = new Canvas(bitmap);view.draw(canvas);return bitmap;}
以上就是完整代,总体思路就是在图片上画一张图片,这里的图片是用控件绘制生成的图片来作为水印,相较于单纯图片稍微复杂一点,也算是一种记录。
需要用到的朋友可以直接使用。