0

How can I add another smaller image as a watermark of a larger image using Xamarin.Android c# and save the output (JPEG/JPG) image to either internal/external storage of an android device.

Bismarck
  • 115
  • 1
  • 8

1 Answers1

0

Using Canvas.DrawBitmap you can draw a Bitmap on top of another mutable Bitmap. Bitmap.CompressAsync provides an overload that allows saving to stream (a FileStream in this case).

var filename = System.IO.Path.Combine(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads).ToString(), "filename.png");

Bitmap newBitmap;
using (var aBitmapToApplyWaterMarkTo = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.Alexina))
using (var waterMarkBitmap = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.watermark))
{
    newBitmap = aBitmapToApplyWaterMarkTo.Copy(aBitmapToApplyWaterMarkTo.GetConfig(), true);
    using (var canvas = new Canvas(newBitmap))
    {
        canvas.DrawBitmap(waterMarkBitmap, newBitmap.Width - 100, newBitmap.Height - 100, null);
    }
}
using (var fileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
{
    await newBitmap.CompressAsync(Bitmap.CompressFormat.Png, 100, fileStream);
}
newBitmap.Dispose();

Note: Using statements are broken into smaller groups to allow disposing of resources as we are finished with them to reduce the total memory consumption of this process...

SushiHangover
  • 73,120
  • 10
  • 106
  • 165