An image can be written to the Response. This allows the image to be displayed only in certain cases. We use an ASPX page or an ASHX handler to display it.
When you use the Response.Write
method in ASP.NET, it replaces the actual web forms in your ASPX page. Add an image to the root of your website project in Visual Studio.
Let's examine the code-behind for writing an image to the output. We must the web page where your image is located. We use a method called MapPath
.
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string loc = Server.MapPath("~/Name.png"); Response.WriteFile(loc); Response.ContentType = "image/png"; } }
The code is from default.aspx.cs
—it uses Server.MapPath
. Server is an intrinsic object on the Page class
, and it has a method called MapPath
.
virtual
path. The string
"~/Name.png" indicates a file called Name.png at the root of your application.Response.WriteFile
is used. This method writes the contents of the file Name.png to the output. It writes the raw binary of the file.ContentType
The code sets the ContentType
property. This property tells the browser the type of the binary—this can help with some encoding errors.
Default.aspx
. The entire contents of Default.aspx
are replaced with the image written to the Response.We rendered image data to the response buffer in an ASP.NET web application. Use this kind of code for writing images to output—this code works well and is fast.