Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Resize image canvas (keeping original pixel dimensions of source image)

My goal is to take an image file and increase the dimensions to the next power of two while preserving the pixels as they are (aka not scaling the source image). So basically the end result would be the original image, plus additional white space spanning off the right and bottom of the image so the total dimensions are powers of two.

Below is my code that I'm using right now; which creates the image with the correct dimensions, but the source data is slightly scaled and cropped for some reason.

// Load the image and determine new dimensions
System.Drawing.Image img = System.Drawing.Image.FromFile(srcFilePath);
Size szDimensions = new Size(GetNextPwr2(img.Width), GetNextPwr2(img.Height));

// Create blank canvas
Bitmap resizedImg = new Bitmap(szDimensions.Width, szDimensions.Height);
Graphics gfx = Graphics.FromImage(resizedImg);

// Paste source image on blank canvas, then save it as .png
gfx.DrawImageUnscaled(img, 0, 0);
resizedImg.Save(newFilePath, System.Drawing.Imaging.ImageFormat.Png);

It seems like the source image is scaled based on the new canvas size difference, even though I'm using a function called DrawImageUnscaled(). Please inform me of what I'm doing wrong.

like image 898
Game_Overture Avatar asked May 10 '11 21:05

Game_Overture


1 Answers

The method DrawImageUnscaled doesn't draw the image at the original pizel size, instead it uses the resolution (pixels per inch) of the source and destination images to scale the image so that it's drawn with the same physical dimensions.

Use the DrawImage method instead to draw the image using the original pixel size:

gfx.DrawImage(img, 0, 0, img.Width, img.Height);
like image 62
Guffa Avatar answered Sep 17 '22 21:09

Guffa