在c#中调整图像大小(实际的kb / mb大小) [英] Resize a an image (its actual kb/mb size) in c#`
问题描述
这是我用来调整图像大小的代码(实际的kb / mb大小)
This is the code I am using to resize an image (the actual kb/mb size)
public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
但是当我使用这段代码时,它实际上会使图像大小(kb大小)大于它的大小。虽然物理尺寸(宽x高)较小。
我哪里错了?
But when I use this code, it actually makes the image size(kb size) bigger than what it was. Although the physical size (width x height) is smaller.
Where am I going wrong?
推荐答案
首先要做的就是看根据你的数字:在线上设一个断点:
The first thing to do is look at your numbers: put a breakpoint on the line:
var newImage = new Bitmap(newWidth, newHeight);
并使用调试器来检查newHeight,newWidth和比率
我怀疑它们不会是你所期望的。
您是否认为当前图像中的高度低于maxHeight?
BTW:你怎么知道kb / mb的尺寸更大?您是保存新图像还是比较文件大小?如果是这样,它们是同一类型的文件,还是未压缩的格式?
and use the debugger to examine newHeight, newWidth, and ratio
I suspect that they will not be what you expect.
Have you considered what happens in your current image has a lower height than maxHeight?
BTW: How do you know the kb / mb size is bigger? Are you saving the new image and comparing file sizes? If so, are they the same type of file, and an uncompressed format?
你应该检查原始图像的 PixelFormat
并且调整后的大小相同(例如:位图构造函数( Int32,Int32,PixelFormat) [ ^ ])。
You should check that the PixelFormat
of the original image and of the resized one are the same (see, for instance: Bitmap Constructor (Int32, Int32, PixelFormat)[^]).
我决定使用我当前的代码。我观察到的是,例如2MB的更大图像被调整为更小的KB尺寸,80KB的更小图像变得更大。
BillWoodruff在评论中说的可能是什么正在这里发生。我不知道是否有一个修复,但现在我会按原样使用它,因为它使得非常大的文件至少要小一点
I decided to use the current code that I have. What I observed is that bigger images for example 2MB gets resized to a smaller KB Size and smaller images of 80KB get bigger.
What BillWoodruff said in a comment is probably what is happening here. I don't know if there is a fix for this but for now i'll use it as is because it makes very big files atleast a little bit smaller
这篇关于在c#中调整图像大小(实际的kb / mb大小)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!