Wednesday, December 14, 2011

ASP.net load an image from embedded resource

Below is a simple method that I couldn't find anywhere else online that loads a .gif image from an embedded resource and returns the image as the web page response


private static void WriteGifImageToResponse(HttpContext context, string resourcePath)
{
    HttpResponse response = context.Response;
    response.ContentType = "image/gif";
 
    Assembly asm = Assembly.GetExecutingAssembly();
    using (Stream imageStream = asm.GetManifestResourceStream(resourcePath))
    {
        using (Image theImage = Image.FromStream(imageStream))
        {
            theImage.Save(context.Response.OutputStream, ImageFormat.Gif);
        }
    }
}

2 comments:

  1. There is another alternative. This alternative works great in server controls that need to access embedded resource.

    If you specify the embedded resource as an web resource, you can access it using a special url.

    In your AssemblyInfo.cs, add a using statement for System.Web.UI and a WebResource attribute for each embedded resource you need to access.

    using System.Web.UI;
    [assembly: WebResource("Your.Resource.Path.gif", "image/gif")]

    Then use the link returned from Page.ClientScript.GetWebResourceUrl(typeof(ATypeInYourAssembly), "Your.Resource.Path.gif")
    to reference the resource.

    I also posted this to my blog.

    ReplyDelete
  2. Great tip David. In my scenario I was making a .dll for reuse in other systems, and didn't want the end users to have to worry about modifying AssemblyInfo.cs.

    ReplyDelete