Scott Hanselman

NuGet Package of the Week #1 - ASP.NET Sprite and Image Optimization

March 07, 2011 Comment on this post [22] Posted in ASP.NET | ASP.NET MVC | NuGet | NuGetPOW
Sponsored By

I was thinking since the NuGet .NET package management site is starting to fill up that I should start looking for gems (no pun intended) in there. You know, really useful stuff that folks might otherwise not find. I'll look for mostly open source projects, ones I think are really useful. I'll look at how they built their NuGet packages, if there's anything interesting about the way the designed the out of the box experience (and anything they could do to make it better) as well as what the package itself does.

Sprite and Image Optimization Preview 3

First, I noticed that the ASP.NET Sprite and Image Optimization preview has been updated to Preview 3. These is an example of something that Microsoft might ship with a future version of ASP.NET, but that you can use today. It's even easier because it's in NuGet.

Install-Package AspNetSprites-MvcAndRazorHelper

They've structured this nicely. There are three packages, in fact, with the "leaf" packages depending on the Core.

image This is an API for ASP.NET to automatically generating CSS sprites and inline images. It works in ASP.NET WebForms, MVC as well as Web Pages. Nice example if you're writing a library of your own and you want it to work for all three ASP.NET techniques (remember it's all ASP.NET). All the source is up there.

The idea behind sprites is that if you've got a page with dozens or even hundreds of small images, perhaps icons on the page, you'll be paying for all those HTTP requests. Instead, why not retrieve a single image with the little ones oriented in a grid, then let the browser break them up at runtime with CSS as "sprites." However, the actual creation of those original grid-like images are often a hassle.

Not only do you have to make the original images, you'll also need to create a CSS file with the relative positions of the image you want in the source image.

You can also do "inline" images in some new browsers by base-64 encoding small images and putting them inside the img tag on the page itself.

Example of an inline image 

ASP.NET Sprites in WebForms

They include a helpful readme.txt (this is a best practice) in the App_Sprites folder that is created when you install the package. Here's the readme. It's nice because it really tells you everything you need to know AND includes pointers to docs. You'd be surprised how few packages do even this. Remember that your NuGet user is likely either IN Visual Studio or NEAR Visual Studio, and since NuGet exists to prevent us from hunting for stuff, don't make your user hunt for things.

For detailed information on ASP.NET Sprites and the Image Optimization Framework, go to http://aspnet.codeplex.com/releases/view/61896

QUICK START:

1) Add your images to the "App_Sprites" directory.
2) Depending on your application type:

****************************
*** ASP.NET Web Forms 4 ****
****************************



**********************************
*** ASP.NET MVC 3 (ASPX Views) ***
**********************************

<%: Sprite.ImportStylesheet("~/App_Sprites/") %>
<%: Sprite.Image("~/App_Sprites/YOUR_IMAGE.jpg") %>

********************************************************
*** ASP.NET MVC 3 (Razor Views) or ASP.NET Web Pages ***
********************************************************

@Sprite.ImportStylesheet("~/App_Sprites/")
@Sprite.Image("~/App_Sprites/YOUR_IMAGE.jpg")

I fire up Visual Studio and make a new ASP.NET WebForms project. Remember I can use NuGet from the command line, from within VS with a dialog, or from within VS using PowerShell.

I right-click on the References folder in the Solution Explorer, and search for "Sprite" online. I'll install the AspNetSprites-WebFormsControl.

Add Library Package Reference (19) 

Now, I just add some images to the App_Sprites folder. Here's my images in Explorer:

App_Sprites

Next, I just run the application once. Look at the same folder now. Note the sprite0.png? (Of course there are settings you can override.) See how the new sprite file is a merge of all the little images?

App_Sprites (21)

There's also new .CSS files as well with new CSS classes to access each one. Very cool.

.camera-png
{
width:48px;
height:48px;
background-image:url(sprite0.png);
background-position:-0px -0px;
}

However, with WebForms I never have to worry about this stuff. Remember that WebForms is about controls. I can add this control and WebForms will handle the IMG tag and the CSS tag.

ImageUrl="~/App_Sprites/video.png" />

And the image is output like this for maximum compatibility.

Pretty cool.

ASP.NET Sprites in ASP.NET MVC (as a Razor Helper)

Now, if I do the same thing, except install-package AspNetSprites-MvcAndRazorHelper in an ASP.NET MVC project.

For an ASP.NET MVC project, I add the CSS manually in the of my _Layout.cshtml:

@Sprite.ImportStylesheet("~/App_Sprites/")

And then I use the Sprite helper wherever I want see an image:

@Sprite.Image("~/App_Sprites/video.png")

Works exactly the same as the WebForms one, except the usage feels more like MVC. Again, this package is a nice example of how one library can be made available for WebForms, WebPages and MVC.

Feel free to recommend cool NuGet libraries in the comments and I'll add them to what I expect will be a very large queue!

Related Links

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
March 07, 2011 9:56
Wow, that's easy. Thanks for sharing.
non
March 07, 2011 9:56
This is pretty nifty, but are the resulting images optimised at all? Is it possible to control output type, opacity, level of detail/quality, etc?

I'm not being picky, just interested :)
OJ
March 07, 2011 10:03
Thank you so much. This is very simple.
March 07, 2011 10:12
OJ - Sure, read the docs. There's a settings.xml with all that stuff that you can put on a per-directory basis.
March 07, 2011 11:28
I read few article on CSS sprite before, but this is the simplest one I have seen so far.

Thanks Scott :)
March 08, 2011 18:48
Am I being a little stupid by expecting this to have the ability to add alt text/other HTML attributes?!
March 08, 2011 23:17
Thank you so much.

I tried this sprite in my application, but i was able to see the image in IE8 with compatibility view enabled and also not able to view the image in Firefox. Am i missing something?

I appreciate the help.
March 09, 2011 0:14
Dan and Sundar - Talk to Mark Berryman, the author, if you have questions or bugs!
March 09, 2011 0:20
I found the issue. My aspx contains the below line in its header

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

On removing this, it worked.
March 12, 2011 15:59
How does this perform with regard to search engines who index images?
March 13, 2011 7:12
Thanks Scott!

If it wasn't for this blog posting, I may have never taken the time to explore this package. I'm a huge fan of this tool!
March 14, 2011 20:11
Good Job!

The dev story is the best thing coming out of MS right now.
March 15, 2011 14:32
Thanks for your nice and Helpfull posts.
I wonder where the ImageOptimizationModule is registered or this is done programmatically and how?.
March 16, 2011 12:22
Is this what Haack's intern was working on? Very nice work!
March 18, 2011 5:19
Great stuff, thank you.
March 22, 2011 17:26
I've done a tool that does this with an enhanced level of customization.
Have a look at:
http://www.codeproject.com/KB/HTML/SpritesAndCSSCreator.aspx

Cheers!
Alex
March 23, 2011 17:32
Hey isn't it the same thing that we saw before in a channel9 video i think his name is Morgan the Phil Haack's Canadian intern he was doing something similar isn't it???
March 23, 2011 19:41
Yep, this is what the Canadian Intern was working on, then a full time employee finished it up.
April 11, 2011 6:00
is it possible to use other folder name (not App_Sprites)?
April 12, 2011 21:22
Paul - Sure, I think you can change it as an option. Plus, the source is available.
September 01, 2011 22:35
Scott does this work with mvc 2?
September 20, 2011 19:36
I'd also encourage people to try my OSS project RequestRecuce http://www.requestreduce.com. It was actually inspired by this project. The difference is that it will do the spriting on the fly without any need to change code or arrange your images and css in special folders. It will also perform color optimizations and run the sprite through optipng producing a MUCH smaller PNG. It works with any asp.net implementation (MVC/Web Forms/Razor/Static Html). Currently, it only works with background images and does not touch the foreground images.

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.