image - ASP.NET MVC 如何优化数百个图像以减少 http 请求

标签 image http optimization request

我有一个网站,它显示数百个带有 JPEG 文件的产品目录(文件大小 40kb - 150kb)。我意识到我的网站生成数百个 http 请求。您知道如何在 asp.net MVC 中优化数百张图片吗?

最佳答案

  1. 将图片以 Base64 编码嵌入页面,而不是使用它们的 URL。这将减少网络浏览器必须发出的 http 请求数。

    http://lucdebrouwer.nl/how-to-base64-encode-your-images/

  2. 压缩您的页面。

    http://developer.yahoo.com/performance/rules.html

更新:这是在 Asp.Net MVC 中将 Image 对象转换为 Base64 的方法

    private string ImageToBase64(Image image,
                                 ImageFormat format)
    {
        using (var ms = new MemoryStream())
        {
            // Convert Image to byte[]
            image.Save(ms, format);
            byte[] imageBytes = ms.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }

    private Image Base64ToImage(string base64String)
    {
        // Convert Base64 String to byte[]
        byte[] imageBytes = Convert.FromBase64String(base64String);
        using (var ms = new MemoryStream(imageBytes, 0,
                                         imageBytes.Length))
        {
            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            return image;
        }
    }

然后你像这样使用它:

<img src="data:image/jpeg;base64,' + yourImageBase64string + '" />

请记住,如果不压缩您的页面,这样做可能不会使您的页面加载得更快。为什么不能只显示这些图像的一个子集并让用户在它们之间导航?

关于image - ASP.NET MVC 如何优化数百个图像以减少 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9238048/

相关文章:

jquery - 我有一个 89x89px 的重复背景方形图像,我想在鼠标悬停时将其更改为随机彩色图像

c# - 如何在 Windows 10 UWP 中复制和调整图像大小

node.js - 如何查看 NTLM type3 消息? (node.js)

c++ - CPU 周期计数 C++

c++ - float 学矢量化,但整数数学不

image - JasperReports 中图像的 Alt

ios - 如果字符串包含某些字符,Swift 会删除扩展字符吗?

javascript - 不存在 'Access-Control-Allow-Origin' header 。 origin因此不允许访问

HTTP PUT 方法结构示例

optimization - 为什么大多数语言不能优化 “0 * …”,并且有任何语言可以优化?