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 开发者_Python百科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.
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);
Use DrawImage
instead, with one of the overloads where you explicitly specify the destination rectangle (using the same-size rectangle as the original source image).
See: http://support.microsoft.com/?id=317174
精彩评论