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); } } }
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
Labels:
Code
Subscribe to:
Post Comments (Atom)
There is another alternative. This alternative works great in server controls that need to access embedded resource.
ReplyDeleteIf 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.
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