Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphics.DrawImage logo scaling incorrectly on a large image

Tags:

c#

graphics

I'm doing some standard code, I am applying a logo to an image and it is working fine.

The source image is always 1024 x 768 as the code before this takes the image and resizes it (creates a new file based on the original).

The logo is applied correctly on some images I have that are 2288 x 1712. If I use an image of 3264 x 2448 then the logo is added at the correct start co ordinates but carries on the x and y axis.

The logo should have a 10px gap between the sides. The 2 letters in the logo that you can see are also far larger than the source image logo.

alt text

If I take the image that is doing the wrong behaviour (3264 x 2448) and change it to 2288 x 1712 and then run the code, it outputs the correct result!

I do not understand because the variable sourceImg is always the 1024 x 768 version so why should resizing the original image have an impact?

Image sourceImg = Image.FromFile(Path.Combine(filepath,filename));
Image logo = Image.FromFile(watermark);

Graphics g = Graphics.FromImage(sourceImg);
g.DrawImage(
   logo,
   sourceImg.Width - horizontalPosition - logo.Width,
   sourceImg.Height - verticalPosition - logo.Height
);
g.Dispose();
logo.Dispose();

sourceImg.Save(Path.Combine(filepath, filename));
sourceImg.Dispose();
like image 422
KevinUK Avatar asked Jan 24 '23 14:01

KevinUK


1 Answers

The overload of the DrawImage that you are using takes the PPI values of the images to calculate the size. As the PPI value of the logo is lower than the PPI value of the image, the logo is scaled up so that their relative physical size (inches instead of pixels) are the same.

Use an overload where you specify the size in pixels:

g.DrawImage(
   logo,
   sourceImg.Width - horizontalPosition - logo.Width,
   sourceImg.Height - verticalPosition - logo.Height,
   logo.Width,
   logo.Height
);
like image 187
Guffa Avatar answered Jan 26 '23 03:01

Guffa