You need to enable JavaScript to run this app. Android开发:如何为拍摄的图像添加底部居中的水印效果?
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何为拍摄的图像添加底部居中的水印效果?

问题描述

作为Android开发新手,希望在拍摄得到的图像上添加水印效果,排查解决方案两天仍未成功实现在拍摄图像上添加水印,需要排查现有代码的问题。
核心需求:将水印效果添加在图像的底部中间位置。

现有实现代码

private void onCaptureImageResult(Intent data) {
    Bitmap photo;
    Bitmap watermark_bitmap = null;
    String selectedFilePath = null;
    if (data.getExtras().get("data") != null) {
        photo = (Bitmap) data.getExtras().get("data");
        watermark_bitmap = Utilities.mark(this, photo, "Hello World", true);
        Uri contentUri = Utilities.getImageUri1(this, watermark_bitmap);
        selectedFilePath = ImageFilePath.getPath(this, contentUri);
        newMeter_image.setImageBitmap(watermark_bitmap); 
    }
}

public static Bitmap mark(Context context, Bitmap src, String watermark, boolean underline) {
    int w = src.getWidth();
    int h = src.getHeight();
    Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());

    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);

    Paint paint = new Paint();
    int color = ContextCompat.getColor(context, R.color.black);
    paint.setColor(color);
    paint.setAlpha(1);
    paint.setTextSize(5);
    paint.setAntiAlias(true);
    paint.setUnderlineText(underline);
    canvas.drawText(watermark, 50,50, paint);
    return result;
}

代码问题排查

  • 文字尺寸过小:设置的文字大小为5像素,在手机拍摄的大尺寸照片上几乎无法被识别,是水印不可见的核心原因
  • 透明度参数错误:Alpha值范围为0-255,设置为1时文字几乎完全透明,哪怕文字尺寸足够也无法被看到
  • 位置不符合需求:当前绘制坐标为(50,50),对应图片左上角距离边缘50像素的位置,和要求的底部居中位置偏差极大
  • 原图配置兼容性问题:如果原Bitmap的配置为空,createBitmap时会出现空指针异常,需要适配Bitmap的可编辑状态

适配需求的修正实现

public static Bitmap mark(Context context, Bitmap src, String watermark, boolean underline) {
    // 基于原图创建可编辑的Bitmap副本,避免直接修改原图导致的兼容性问题
    int w = src.getWidth();
    int h = src.getHeight();
    Bitmap result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(src, 0, 0, null);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // 黑色文字搭配适中透明度,既不遮挡原图也能清晰识别
    paint.setColor(ContextCompat.getColor(context, R.color.black));
    paint.setAlpha(180);
    // 根据原图宽度自适应设置文字大小,适配不同分辨率的拍摄图片
    paint.setTextSize(w / 20f);
    paint.setUnderlineText(underline);

    // 计算居中绘制的X坐标:图片宽度减去文字宽度后均分两侧边距
    float textWidth = paint.measureText(watermark);
    float centerX = (w - textWidth) / 2;
    // 计算底部绘制的Y坐标:距离图片底部保留1/20高度的边距,同时适配文字的实际绘制基线
    float bottomY = h - (h / 20f) - paint.descent();

    canvas.drawText(watermark, centerX, bottomY, paint);
    return result;
}

额外提示:通过data.getExtras().get("data")获取的是系统相机返回的缩略图,如果需要保存全尺寸的带水印拍摄照片,需要在调用相机时指定保存路径,从指定路径读取全尺寸原图后再做水印绘制。

内容的提问来源于stack exchange,提问作者Krish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.03 10:27:03