This project has moved and is read-only. For the latest updates, please go here.

How to draw a transparent rectangle at a specific location, on a specific image?

Apr 21, 2014 at 4:52 PM
Edited Apr 21, 2014 at 4:54 PM
Hi,

I'm trying to draw a transparent rectangle on a specific image using the below code.
private static MagickImage ApplyWatermark(MagickImage image, string waterMarkText) {
    var backgroundOfWaterMark = new MagickImage(new MagickColor("#FFFFFF"), image.Width, 20) { Format = MagickFormat.Png };
    var img = image;
    img.Composite(backgroundOfWaterMark, 0, img.Height - 20);
    img.Format = MagickFormat.Png;
    var font = new DrawableFont("Batang");
    var text = new DrawableText(3, img.Height - 7, waterMarkText);
    var size = new DrawablePointSize(13);
    var fillColor = new DrawableFillColor(new MagickColor("#000000"));
    image.Draw(font, size, fillColor, text);
    backgroundOfWaterMark.Dispose();
    image.Dispose();
    font.Dispose();
    text.Dispose();
    size.Dispose();
    fillColor.Dispose();
    return img;
}
And I'm always ended up with a NOT transparent regular white rectangle. The part of the code that draws a text on that rectangle is working just fine. My problem is only that I need that rectangle to be a transparent/ opacity 0.5.

How can I do this? How can I do a white background with 50% opacity?

Thanks.
Apr 21, 2014 at 4:58 PM
Edited Apr 21, 2014 at 5:00 PM
The hex color notation also supports the alpha channel. Changing the color of backgroundOfWaterMark to "#FFFFFF80" should get you the color that you want. I will update the documentation to explain this better.
Apr 21, 2014 at 5:28 PM
Edited Apr 21, 2014 at 5:30 PM
Thanks for a quick reply.

I've changed the code as follows.
var backgroundOfWaterMark = new MagickImage(new MagickColor("#FFFFFF80"), image.Width, 20) { Format = MagickFormat.Png };
No luck. I still ended up with a regular white background. The sample is here.

BTW: Can an Image format (MagickFormat.Png) has any relationship or effect the result I'm trying to achieve? Maybe the problem is here?
Apr 21, 2014 at 6:09 PM
I missed it the first time but after reading your code again I noticed you did not specify the CompositeOperator. The default is In but you need Over:
img.Composite(backgroundOfWaterMark, 0, img.Height - 20, CompositeOperator.Over);
Apr 21, 2014 at 6:19 PM
That did the trick. Thanks so much!

PS: Even thought the there is no helpful documentation on Magick.NET, the forum is pretty good with fast reply. :D