Android为非常大的jpg文件添加水印徽标(比如10000 x 150000)

时间:2015-01-21 08:20:51

标签: java android bitmap jpeg

我有一个大的jpeg文件说10000 x 150000 px。我想在图像的底部添加一个小徽标,而不需要重新调整大小。

我能够做到这一点如果我对原始图像进行采样并使用canvas绘制徽标。但是当我最终将其保存到文件时,图像原始尺寸将随着我的采样而减少。

如果我将原始图像加载到位图而不进行下采样,则会超出VM。

3 个答案:

答案 0 :(得分:1)

以下代码为我工作: -

public static Bitmap mark(Bitmap src, String watermark, Point location, Color color, int alpha, int size, 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();
    paint.setColor(color);
    paint.setAlpha(alpha);
    paint.setTextSize(size);
    paint.setAntiAlias(true);
    paint.setUnderlineText(underline);
    canvas.drawText(watermark, location.x, location.y, paint);

    return result;
}

答案 1 :(得分:1)

对于大型图片编辑,您需要使用imagemagick等原生工具。因为在Android支持的Java中似乎缺乏高级图像处理库。

如果你可以为android编译Composite工具的二进制文件。然后,您可以使用--limit选项来处理有限的内存。

此外,您可以尝试OpenCV作为替代方案。

答案 2 :(得分:0)

处理大图像文件时可以使用BitmapRegionDecoder。来自official document

  

BitmapRegionDecoder可用于解码图像中的矩形区域。当原始图像很大并且您只需要部分图像时,BitmapRegionDecoder特别有用。   要创建BitmapRegionDecoder,请调用newInstance(...)。给定BitmapRegionDecoder,用户可以重复调用decodeRegion()以获取指定区域的解码位图。

只需解码图像中需要添加水印的部分,然后使用Canva在其上绘制文字。

try {
    BitmapRegionDecoder regionDecoder = BitmapRegionDecoder.newInstance("/sdcard/test.png", true);
    Bitmap bitmap = regionDecoder.decodeRegion(rect, options);
} catch (IOException e) {
    e.printStackTrace();
}