我继承了一个代码,它在宽度和高度上调整图像大小 . 我还观察到,即使图像高度和宽度增加,它也会减小文件大小 . 这是保存图像的调整大小代码和调用功能代码
例如,它可能更好地解释 . 我有原始图像,709 * 653像素和文件大小670 kb
调整大小后,它是1000 * 921,这是预期的,但它的大小是176 kb
Image orgImage = Image.FromFile(originalimagepath);
//resizes image using below function
transformedImage = ImageUtils.resizeImage(orgImage, Settings.MaxLargeImage);
memstrImage = new MemoryStream();
//saves image to memorystream which is in turn saved in destination as resized image.
transformedImage.Save(memstrImage,ImageFormat.Jpeg);
public static Image resizeImage(Image imgToResize, int resizeType)
{
//resizetype is maximum resize width I want image to take.
int height = imgToResize.Height;
int width = imgToResize.Width;
float ratio = 0;
Size size = new Size();
if (height >= width)
{
ratio = ((float)resizeType / (float)height);
}
else
{
ratio = ((float)resizeType / (float)width);
}
size.Height = Convert.ToInt32((float)ratio * (float)imgToResize.Height);
size.Width = Convert.ToInt32((float)ratio * (float)imgToResize.Width);
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destHeight = Convert.ToInt32(sourceHeight * nPercent);
int destWidth = Convert.ToInt32(sourceWidth * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
我假设,并且可以看到纵横比没有受到损害,但建议保持原样,或者当图像高度和宽度增加时,理想情况下文件大小应该增加是否合乎逻辑
对于这个问题,我希望在高度和宽度增加时增加文件大小,但欢迎提供最佳实践建议 .
有什么建议?
2 回答
您将调整大小的图像保存为Jpeg格式 . Jpeg是一种"lossy"格式,这意味着,为了节省空间,保存的图像只是内存中位图的近似值,所选择的位置使其看起来像是人眼的原始图像 . 如果你只是使用Image.Save()来保存你的位图,那么"storage quality"被认为是75,根据这篇文章:What quality level does Image.Save() use for jpeg files? . (无论如何,没有记录Jpeg格式的
Image.Save()
的质量 . )因此,如果您调整位图大小并将其保存到Jpeg,则生成的文件可能比原始文件小,或者更大,因为压缩,与维度的更改无关 . (尽管尺寸的大变化最终将主导任何压缩问题,因为位图的原始尺寸随着像素尺寸的缩放而呈二次方增加 . )
如果要在保存JPG时尝试质量设置如何影响文件大小,可以使用此方法:
这显然是以不同的图像格式保存(bmp或png vs jpg)或使用不同的JPG压缩强度 .
您应该在加载图像时记下图像的格式,并以相同的格式保存 . 或者在保存jpg时确保使用不同的抗压强度 . 查看更多here .