我的目标是获取一个图像文件并将尺寸增加到二的下一个幂,同时保持像素原样(也就是不缩放源图像)。所以基本上最终结果将是原始图像,加上跨越图像右侧和底部的额外空白,因此总尺寸是 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);
源图像似乎是根据新的 Canvas 大小差异缩放的,即使我使用的是名为 DrawImageUnscaled() 的函数。请告诉我我做错了什么。
最佳答案
DrawImageUnscaled
方法不会以原始像素大小绘制图像,而是使用源图像和目标图像的分辨率(每英寸像素数)来缩放图像,以便绘制图像相同的物理尺寸。
改为使用 DrawImage
方法使用原始像素大小绘制图像:
gfx.DrawImage(img, 0, 0, img.Width, img.Height);
关于C# - 调整图像 Canvas 大小(保持源图像的原始像素尺寸),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5956965/