缩小图像质量损失

Shrinking Image Quality Loss

本文关键字:损失 图像质量 缩小      更新时间:2023-09-26

我在JS轮播中显示图像。图像非常大,所以我在HTML中缩小了它们。我做了一些数学来保持纵横比。最后,尽管这些大图像的质量会降低。应该注意的是,这些图像已经存在于服务器中,我不应该更改原始文件的大小。

是什么原因导致这种质量下降?我应该坚持使用较小尺寸的图像,增加将显示的最终尺寸吗?这是帮助的代码,最大宽度和高度目前分别为 270 和 180。所有这些都是 C#。

// srcccccc is the image file. Can be any kind of extension jpg, png, etc.
if (srcccccc != "")
{
    Globals.NavigateURL();
    string path = PortalSettings.HomeDirectory + srcccccc;
    using (System.Drawing.Image img = System.Drawing.Image.FromFile(@Server.MapPath(path)))
    {
        int[] newSizes = ResizeWithRatio(img);
        contentsall += "<img src='"" + PortalSettings.HomeDirectory + srcccccc + "'" alt='"Image "
            + folderidddin + "'" height='"" + newSizes[1] + "px'"" + "'" width='"" + newSizes[0] + "px'" />";
    }
}
// HTML is dynamically added later....
private int[] ResizeWithRatio(System.Drawing.Image img)
{
            int[] sizes = new int[2];
            if (img.Width > maxWidth || img.Height > maxHeight)
            {
                float ri = (float)img.Width / (float)img.Height;
                float rs = (float)maxWidth / (float)maxHeight;
                if (rs > ri)
                {
                    sizes[0] = (int)((float)img.Width * (float)maxHeight / (float)img.Height);
                    sizes[1] = maxHeight;
                }
                else
                {
                    sizes[0] = maxWidth;
                    sizes[1] = (int)((float)img.Height * (float)maxWidth / (float)img.Width);
                }
            }
            else
            {
                sizes[0] = img.Width;
                sizes[1] = img.Height;
            }
            return sizes;
}

您遇到的问题是您根本没有缩放图像,而是告诉 Web 浏览器拍摄全尺寸图像并将其渲染得更小。可悲的是,浏览器在这方面不是很擅长,我认为只需使用非常简单的算法来做到这一点。

解决方案是缩放服务器上的图像。我建议有一个页面处理程序,它以某种方式(文件名、id 等)接收图像引用,并在输出到客户端之前进行大小调整。以下问题涉及 c# 中的缩放。

高质量图像缩放库

最好缩小图像服务器端,请查看此文档。这将节省网络流量并创建更高质量的图片。