C# - 调整图像画布大小(保持源图像的原始像素尺寸)

Gam*_*ure 12 c# graphics drawing image image-processing

我的目标是拍摄一个图像文件并将尺寸增加到下一个2的幂,同时保留像素(也就是不缩放源图像).所以基本上最终结果将是原始图像,以及跨越图像右侧和底部的额外白色空间,因此总尺寸是2的幂.

下面是我正在使用的代码; 这会创建具有正确尺寸的图像,但源数据会因某种原因略微缩放和裁剪.

// 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);
Run Code Online (Sandbox Code Playgroud)

看起来源图像是根据新的画布大小差异缩放的,即使我使用的是一个名为DrawImageUnscaled()的函数.请告诉我我做错了什么.

Guf*_*ffa 17

该方法DrawImageUnscaled不会以原始pizel大小绘制图像,而是使用源图像和目标图像的分辨率(每英寸像素数)来缩放图像,以便使用相同的物理尺寸绘制图像.

使用该DrawImage方法代替使用原始像素大小绘制图像:

gfx.DrawImage(img, 0, 0, img.Width, img.Height);
Run Code Online (Sandbox Code Playgroud)