Search code examples
c#imagewatermark

C# change watermark image size depending upon original image


I'm watermarking my images before uploading. the problem im facing is if the image is small, the watermark looks to big.. i want to change watermark image size according to the original image..

for e.g. : watermark image should be 30% of the original image. I'm doing this in c#:

imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x,y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));

What am i supposed to do to first get image size and then change watermark image size accordingly ??


Solution

  • Well then...something like:

    Bitmap yourImage = ...;
    Bitmap yourWatermark = ...;
    
    int newWaterWidth = (int)((float)yourImage.Width * .3);
    int newWaterHeight = (int)((float)yourImage.Height* .3);
    
    
    using(Bitmap resizedWaterm = new Bitmap(newWaterWidth, newWaterHeight))
    using(Graphics g = Graphics.FromImage((Image)resizedWaterm))
    {
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.DrawImage(yourWatermark, 0, 0, newWaterWidth , newWaterHeight );
    }
    
    int x = ..., y = ...;
    using(Graphics g2 = Graphics.FromImage((Image)resizedWaterm))
    {
      g2.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
    }
    

    (Not tested, you also need to fill in values at the ... dots)

    Code for resizing from: Resizing an Image without losing any quality

    Hope this helps!