C# - 调整图像画布大小(保持源图像的原始像素尺寸)
我的目标是获取图像文件并将尺寸增加到 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);
似乎源图像是根据新的画布大小差异进行缩放的,即使我使用的是名为 DrawImageUnscaled() 的函数。请告诉我我做错了什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DrawImageUnscaled
方法不会以原始像素大小绘制图像,而是使用源图像和目标图像的分辨率(每英寸像素数)来缩放图像,以便使用相同的物理尺寸绘制图像。方面。使用
DrawImage
方法来使用原始像素大小绘制图像: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:使用
DrawImage
代替,并使用其中显式指定目标矩形的重载之一(使用与原始源图像相同大小的矩形)。请参阅:http://support.microsoft.com/?id=317174
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