简体   繁体   中英

Image compression in ASP.NET MVC

I have a lot of images(about 1,000) in 30kb aproximately, the load size of the index was 45.5mb, if you ask why.

i get the images from a server, then convert to byte array and then to base64 string to send to index in

data:image/webp;base64,{0}

i use this:

Html.Raw(String.Format("data:image/webp;base64,{0}", Convert.ToBase64String(File.ReadAllBytes("\\\\ImageServer\\ImagePathFolder\\Image.JPG".Replace("\\", "\\\\")))))

so far the index takes to load about 24 seconds.

I ask for help to compress the images and get at least the half size now i get.

NOTE: all this code in in ASP.NET MVC with C#

You should return binary-large-objects ("BLOBs", generally anything larger than a kilobyte or so) in a separate request - this has numerous advantages, but the main reasons are

  • Browsers can cache individual responses and images.
  • They can be transferred directly without encoding them using an inefficient format like Base64 (which effectively uses 1 byte to transfer 6 bits of data).

Whereas using data: URIs to include images inline in the page is wasteful because the image data needs to be loaded and encoded to Base64 on every request. Avoid disk IO when you can (additionally your code isn't using Async IO, so it's particularly inefficient).

In ASP.NET MVC and ASP.NET Core, define a new Action to handle requests for images:

[HttpGet("images/{imageName}")]
public ActionResult GetImage( String imageName )
{
    String imagefileName = GetImageFileName( imageName ); // don't forget to sanitize input to prevent directory traversal attacks

    // Use `FileResult` to have ASP.NET MVC efficiently load and transmit the file rather than doing it yourself:
    return new FilePathResult( imagefileName, "image/jpeg" ); // assuming all images are JPEGs.
}

In your page, use an <img /> element like so:

<img src="@( this.Url.Action("GetImage", new { imageName = "foo" } ) )" />

In ASP.NET WebForms you'll need to use an *.ashx instead, but the principle is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM