Create image of Html code with c# - asp.net

I have created html code and then save this html page as an image . The html controls which I have created is showing properly in the image with all images and background color. It is woking fine on localhost.
but I am trying to creating html code to image on the server. the image is creating but it's not showing anything like bgcolor, images, etc.
only blank image is showing.
Code :
Using Ajax calling function from client side I am sending the html content to the serverside
Server Side Method
[System.Web.Services.WebMethod()]
public static void GenerateTemplateImage(string html_Content, string TemplateName)
{
var t = new Thread(MakeScreenshot);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public static void MakeScreenshot()
{
Bitmap bitmap;
string html = string.Empty;
string Title = string.Empty;
string Meta = string.Empty;
string Style = string.Empty;
string ScriptBefore = string.Empty;
string ScriptAfter = string.Empty;
string Scripthead = string.Empty;
html="<div><div id='s_p_box-1' style='background-color: rgb(24, 0, 238); width: 109px; height: 75px;>Welcome </div>' <br/> <img id='template1' class='template' style='border:1px solid green; height:142px;width:116px' src='http://ace.demos.classicinformatics.com/Advertiser-Admin/Campaign/UserTemplate/template1.jpg'></div>";
WebBrowser wb = new WebBrowser();
wb.Navigate("about:blank");
if (wb.Document != null)
{
wb.Document.Write(html);
}
wb.DocumentText = html;
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
// Set the size of the WebBrowser control
// Take Screenshot of the web pages full width
// wb.Width = wb.Document.Body.ScrollRectangle.Width;
wb.Width = 1024;
// Take Screenshot of the web pages full height
// wb.Height = wb.Document.Body.ScrollRectangle.Height;
//wb.Height = 786;
wb.ScrollBarsEnabled = true;
if (wb.Height <= 0)
{
wb.Height = 1024;
}
//if (wb.Width <= 400)
//{
// wb.Width = 700;
//}
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control
//Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
//using (bitmap = new Bitmap(wb.Width, wb.Height))
using (bitmap = new Bitmap(wb.Width, wb.Height))
{
//wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
//string imgPath = HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ImgPath"].ToString());
//string imgPath="C:\\Projects\\aec\\Ace-A-Metric\\Advertiser-Admin\\Campaign\\UserTemplate\\";
string imgPath = URlPath + "test123" + ".bmp";
//bitmap.Save(#"D:\" + txtTempName.Text + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
bitmap.Save(imgPath, System.Drawing.Imaging.ImageFormat.Bmp);
//string imgpath = Path.Combine(HttpContext.Current.Server.MapPath("~") + "Advertiser-Admin\\Campaign\\UserTemplate\\" + txtTempName.Text +".bmp");
//bitmap.Save(imgpath, System.Drawing.Imaging.ImageFormat.Bmp);
}
wb.Dispose();
GC.Collect();
}

Do not use the WebBrowser control, it is shipped with a lot of constraints due its COM legacy, and the very poor object model.
One of the possible solution is to use Awesomium.Net
Espacially, this article explain the process : Capturing Web-Pages With C# (.NET)
The major difference, is that Awesomium and its .Net wrapper is written with no dependency to the host (actually from the Chromium source code). Then the library is actually standalone and let you consider a lots of more scenarios.

Related

Pass generated barcode to an html tag

I've got my function:
protected void Button1_Click(object sender, EventArgs e)
{
var barcodeWriter = new BarcodeWriter();
var encOptions = new ZXing.Common.EncodingOptions() { Width = 200, Height = 200, Margin = 0 };
barcodeWriter.Options = encOptions;
barcodeWriter.Format = BarcodeFormat.CODE_128;
var resultBitmap = new Bitmap(barcodeWriter.Write("hello"));
resultBitmap.Save(#"C:\Users\lrusin\Documents\Visual Studio 2015\Projects\prova_eti\asd.bmp");
}
that generates a barcode image and by now saves it to some folder in my file system.
I was wondering if there is a way to put the generated image (not the one saved in C:\...) into an HTML container like a div or a list.
In my example i will have a button that when is clicked loads into a div the image generated by the code written above.
The easiest way would be to load the generated bitmap into a MemoryStream to get the Byte Array. Then convert the array to Base64 for displaying in HTML. In the snippet below I generate the bitmap for demo purposes.
//create a new empty bitmap
Bitmap resultBitmap = new Bitmap(100, 100);
//fill the bitmap with a red cirle
using (Graphics g = Graphics.FromImage(resultBitmap))
{
g.FillEllipse(Brushes.Red, 10, 10, 80, 80);
}
//no explanation needed here
string base64Image = string.Empty;
//load the bitmap into the memorystream
using (MemoryStream ms = new MemoryStream())
{
resultBitmap.Save(ms, ImageFormat.Bmp);
//get the byte array from the stream and convert to Base64
base64Image = Convert.ToBase64String(ms.ToArray());
}
//display the result
Image1.ImageUrl = "data:image/jpeg;base64," + base64Image;
However it could be that BarcodeWriter has some build-in functions to do this directly...

Resizing Images using HTTP Handler ASP.Net, some images not showing up

I'm at my wits end here.
I've a HTTP Handler (ImageHandler.ashx) that sends down images (resized), its a standard HTTP handler (tried this with Reusable true and false) that uses the Image.GetThumbnailImage to resize and return the thumbnail.
I've an asp Datalist control which has a table with a html image control.
<asp:DataList ID="listImg" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
ShowFooter="false" ShowHeader="false">
<ItemTemplate>
<table width="220px">
<tr width="100%">
<td>
<img src="Scripts/ImageHandler.ashx?width=125&image=Upload/<%# DataBinder.Eval(Container.DataItem, "photo") %>"
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
As you can see the parameters the Handler needs are the width and the Image path.
This Datalist is bound to a datatable (ImageData) which provides the list of images to be displayed.
Well all makes sense so far, now here is the issue - Say I'm loading 5 images, i.e. my ImageData DataTable has 5 rows, it is a given that only 3-4 images will be displayed, the remaining ones just come up with a red X, like when you've no image. Now if you look at the code and navigate to the image src like -
http://localhost:3540/Scripts/ImageHandler.ashx?width=150&image=Upload/Test123.jpg
you'll see the image, they're all there no missing images. Reload and they're back.
I ran this in Firefox and opened up Firebug and when I looked through the Images tab, ALL the images were returned according to Firebug (Status 200 OK and I see the Image in the Response tab), it's like the Webserver just does not display some of them. Note that it is NOT always the images that took the longest to process/load that were missing, its some random ones.
What could be going on here?
Thank you.
EDIT 1- Adding the Handler Code (original), we inherited this code. I've removed Caching from the code here, but FYI thumbnails once generated are cached.
public class ImageHandler : IHttpHandler{
public int _width;
public int _height;
public int _percent;
public string imageURL;
public void ProcessRequest(HttpContext context)
{
try
{
Bitmap bitOutput;
string appPath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ImagePath"]);
String strArquivo = appPath + context.Request.QueryString["image"].Replace("/", "\\");
if (!(String.IsNullOrEmpty(context.Request["width"])))
{
Bitmap bitInput = GetImage(context);
if (SetHeightWidth(context, bitInput))
{ bitOutput = ResizeImage(bitInput, _width, _height, _percent); }
else { bitOutput = bitInput; }
context.Response.ContentType = "image/jpeg";
bitOutput.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
return;
}
catch (Exception ex) { /*HttpContext.Current.Response.Write(ex.Message);*/ }
}
/// <summary>
/// Get the image requested via the query string.
/// </summary>
public Bitmap GetImage(HttpContext context)
{
try
{
if (context.Cache[("ImagePath-" + context.Request.QueryString["image"])] == null)
{
string appPath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ImagePath"]);
appPath = appPath + context.Request.QueryString["image"].Replace("/", "\\");
Bitmap bitOutput;
imageURL = appPath;
bitOutput = new Bitmap(appPath);
return bitOutput;
}
else
{
return (Bitmap)context.Cache[("ImagePath-" + context.Request.QueryString["image"])];
}
}
catch (Exception ex) { throw ex; }
}
/// <summary>
/// Set the height and width of the handler class.
/// </summary>
public bool SetHeightWidth(HttpContext context, Bitmap bitInput)
{
try
{
double inputRatio = Convert.ToDouble(bitInput.Width) / Convert.ToDouble(bitInput.Height);
if (!(String.IsNullOrEmpty(context.Request["width"])) && !(String.IsNullOrEmpty(context.Request["height"])))
{
_width = Int32.Parse(context.Request["width"]);
_height = Int32.Parse(context.Request["height"]);
return true;
}
else if (!(String.IsNullOrEmpty(context.Request["width"])))
{
_width = Int32.Parse(context.Request["width"]);
_height = Convert.ToInt32((_width / inputRatio));
if (_width == 400 &&_height > 500)
{
_height = 500;
_width = Convert.ToInt32(500 * inputRatio);
}
else if (_width == 125 && _height > 200)
{
_height = 200;
_width = Convert.ToInt32(200 * inputRatio);
}
return true;
}
else if (!(String.IsNullOrEmpty(context.Request["height"])))
{
_height = Int32.Parse(context.Request["height"]);
_width = Convert.ToInt32((_height * inputRatio));
return true;
}
else if (!(String.IsNullOrEmpty(context.Request["percent"])))
{
_height = bitInput.Height;
_width = bitInput.Width;
_percent = Int32.Parse(context.Request["percent"]);
return true;
}
else
{
_height = bitInput.Height;
_width = bitInput.Width;
return false;
}
}
catch (Exception ex) { throw ex; }
}
/// <summary>
/// Resizes bitmap using high quality algorithms.
/// </summary>
public static Bitmap ResizeImage(Bitmap originalBitmap, int newWidth, int newHeight, int newPercent)
{
try
{
if (newPercent != 0)
{
newWidth = Convert.ToInt32(originalBitmap.Width * (newPercent * .01));
newHeight = Convert.ToInt32(originalBitmap.Height * (newPercent * .01));
}
Bitmap inputBitmap = originalBitmap;
Bitmap resizedBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format64bppPArgb);
Graphics g = Graphics.FromImage(resizedBitmap);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
Rectangle rectangle = new Rectangle(0, 0, newWidth, newHeight);
g.DrawImage(inputBitmap, rectangle, 0, 0, inputBitmap.Width, inputBitmap.Height, GraphicsUnit.Pixel);
g.Dispose();
return resizedBitmap;
}
catch (Exception ex) { throw ex; }
}
public bool IsReusable
{
get
{
return true;
}
}}
EDIT 2 If someone wishes to test this whole thing out, here is the code that picks up images at random from a predefined folder to create the DataTable (ImageData) that the aspDataList (listImg) is bound to -
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Server.MapPath("Upload"));
System.IO.FileInfo[] files = dirInfo.GetFiles();
int fileCount = files.Length;
System.Data.DataTable ImageData = new System.Data.DataTable();
System.Data.DataColumn dCol = new System.Data.DataColumn("photo");
ImageData.Columns.Add(dCol);
System.Random rnd = new Random();
int nxtNumber = 0;
System.Data.DataRow dRow = null;
string fileName = string.Empty;
for (int i = 0; i < 20; i++)
{
dRow = ImageData.NewRow();
nxtNumber = rnd.Next(fileCount);
while (!files[nxtNumber].Extension.Equals(".jpg"))
{
nxtNumber = rnd.Next(fileCount);
}
fileName = files[nxtNumber].Name;
dRow["photo"] = fileName;
ImageData.Rows.Add(dRow);
}
listImg.DataSource = ImageData;
listImg.DataBind();
try to encode querystring of url, for ex:
http://localhost:3540/Scripts/ImageHandler.ashx?width=150&image=Upload/Test123.jpg
urlencode to
http://localhost:3540/Scripts/ImageHandler.ashx?width%3D150%26image%3DUpload%2FTest123.jpg
I presume your actual code includes the /> at the end of the img tag???
If not you could try adding this first and retesting.
Not really an answer but you could try changing the img tag to an asp:Label and displaying the filename as text rather than displaying the image just to see if the datatable is being constructed correctly. As you are able to see the images when accessing the image handler directly I would say it has something to do with the datatable construction in the codebehind.
When ever I have done anything similar I usually store the images in the SQL DB and use the image handler to return the image with the record id in the query string. This means you are returning a existing table of records rather than having to create one based on the contents of a folder.
Well here is the funny thing - the same code on the server behaves in a more predictable manner, I may still have a couple of missing images, but now it is like 1 missing from say 30-40 on average versus 1 from every 5 in my local environment.
Since these requests were asynchronous could it have something to do with the actual cpu of the machine it was running on, the server was just better adapted to deal with multiple requests versus my measly laptop?
Either ways I've modified the code, so at this point there is no re-sizing involved, the handler code just fetches re-sized images and all is well at this point.
Thank you all for your inputs.

How do I create an image of a webpage and save the image to my server using .net?

I have a page that dynamically generates a small html page containing 1 small table w/text. I want to be able to take a picture (png preferable) of that page and save it to my server.
I was previously using a 3rd party solution (ABCdrawHTML2), but I have changed servers and this one does not have it. Is there a way to do it without 3rd party solutions?
This is how I do it using the Windows.Forms WebBrowser:
public class WebSiteThumbnailImage
{
string m_Url;
int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight;
Bitmap m_Bitmap = null;
public WebSiteThumbnailImage(string url, int browserWidth, int browserHeight, int thumbnailWidth, int thumbnailHeight)
{
m_Url = url;
m_BrowserWidth = browserWidth;
m_BrowserHeight = browserHeight;
m_ThumbnailWidth = thumbnailWidth;
m_ThumbnailHeight = thumbnailHeight;
}
public Bitmap GenerateWebSiteThumbnailImage()
{
Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
private void _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser = new WebBrowser();
m_WebBrowser.ScrollBarsEnabled = false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser = (WebBrowser)sender;
m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled = false;
m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
}
}
To use this, at the appropriate place in your code-behind, do something like:
WebSiteThumbnailImage thumbnail = new WebSiteThumbnailImage(url, 1000, 1000, 200, 200);
Bitmap image = thumbnail.GenerateWebSiteThumbnailImage();
image.Save(filePath);

taking screenshot of an iFrame on button click

Hello i am creating a website having an iFrame and a button.The function of that button is to get the screenshot of whatever that is displayed inside the iFrame and save it as an image on the harddisk.Below is the code i am using
private void saveURLToImage(string url)
{
if (!string.IsNullOrEmpty(url))
{
string content = "";
System.Net.WebRequest webRequest = WebRequest.Create(url);
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.IO.StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
content = sr.ReadToEnd();
//save to file
byte[] b = Convert.FromBase64String(content);
System.IO.MemoryStream ms = new System.IO.MemoryStream(b);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
img.Save(#"c:\pic.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();
ms.Close();
}
}
And here is the code for button click
protected void Button1_Click(object sender, ImageClickEventArgs e)
{
saveURLToImage("http://www.google.com");
}
However when i click on the button i am getting an error
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
on this line
byte[] b = Convert.FromBase64String(content);
i am unable to figure out how to resolve it.Any help would be greatly appreciated.Thank you
In your case content is the raw HTML that makes the page up, not how it is rendered - that would be up to the browser to decide (have a look at it in the debugger) so, since that is not base 64 (which is a way to encode binary data using just ASCII characters), in order for this to work you would need to get the base 64 encoded binary data of a JPEG encoded image of however the browser has rendered the HTML, which you do not have.
I think this is not an easy thing to achieve in a web application since in the .net code you are running on the server and it is the job of the client to render the HTML into something that you can take a screenshot of. You could (and this will probably be really fragile so I would not really recommend it, hosting a winforms control like this in a web application is usually a recipe for trouble, but I think it may be possible) use a browser control on your server side and set the URL of that but then you would need to somehow screenshot it - this might help: Taking Website Screenshots With The WebBrowser Control.
Update
Tucked away in the comments of the web site I linked last is some code that actually works to take a screenshot of a web page (using a WebBrowser control). It requires that you have references to the following:
System.Drawing
System.Windows.Forms
Microsoft HTML Object Library (this is a COM reference, not a .NET one)
Here is a class that does the job we want (has just a single Render method on it that takes a Uri and a Size and returns a Bitmap):
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using mshtml;
public class HtmlToBitmapConverter
{
public Bitmap Render(Uri uri, Size size)
{
var browser = new WebBrowser
{
ScrollBarsEnabled = false,
ScriptErrorsSuppressed = true,
Size = size
};
browser.BringToFront();
NavigateAndWaitForLoad(browser, uri, 0);
var bitmap = new Bitmap(size.Width, size.Height);
GetImage(browser.Document.DomDocument, bitmap, Color.White);
return bitmap;
}
private void NavigateAndWaitForLoad(WebBrowser browser,
Uri uri,
int waitTime)
{
const int sleepTimeMiliseconds = 5000;
browser.Navigate(uri);
var count = 0;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Thread.Sleep(sleepTimeMiliseconds);
Application.DoEvents();
count++;
if (count > waitTime / sleepTimeMiliseconds)
{
break;
}
}
while (browser.Document.Body == null)
{
Application.DoEvents();
}
var document = (IHTMLDocument2)browser.Document.DomDocument;
var style = (IHTMLStyle2)document.body.style;
style.overflowX = "hidden";
style.overflowY = "hidden";
}
private static void GetImage(object obj,
Image destination,
Color backgroundColor)
{
using (var graphics = Graphics.FromImage(destination))
{
var deviceContextHandle = IntPtr.Zero;
var rectangle = new Rect
{
Right = destination.Width,
Bottom = destination.Height
};
graphics.Clear(backgroundColor);
try
{
deviceContextHandle = graphics.GetHdc();
var viewObject = (IViewObject)obj;
viewObject.Draw(1,
-1,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
deviceContextHandle,
ref rectangle,
IntPtr.Zero,
IntPtr.Zero,
0);
}
finally
{
if (deviceContextHandle != IntPtr.Zero)
{
graphics.ReleaseHdc(deviceContextHandle);
}
}
}
}
[ComImport]
[Guid("0000010D-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IViewObject
{
void Draw([MarshalAs(UnmanagedType.U4)] uint dwAspect,
int lindex,
IntPtr pvAspect,
[In] IntPtr ptd,
IntPtr hdcTargetDev,
IntPtr hdcDraw,
[MarshalAs(UnmanagedType.Struct)] ref Rect lprcBounds,
[In] IntPtr lprcWBounds,
IntPtr pfnContinue,
[MarshalAs(UnmanagedType.U4)] uint dwContinue);
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
}
NOTE As I said before, I am not sure this is a great idea to be used in a web application for a couple of reasons:
It is a Windows Forms control so the way it deals with memory may not be compatible with being used in a web application.
It means that the account taking the screenshot will be the one that the web application is running as, not necessarily the end user.
OK, so I think the above would be fine in a winforms app but maybe not appropriate for the web, but, hey, we can make it work anyway, here goes...
I am assuming you are going for a regular ASP .NET web application in which case you would have something like this in the .aspx page:
<asp:Button runat="server" OnClick="TakeScreenShot" Text="Take Screenshot"/>
Then in the code behind the TakeScreenshot method would look like this:
protected void TakeScreenShot(object sender, EventArgs e)
{
Uri uri = new Uri("http://www.google.com");
// Because it is a WebBrowser control it needs to run in an STA
// thread - what we will do is render the image to a Bitmap then
// store the raw bytes in this byte array from a newly created
// thread
byte[] screenshot = null;
var t = new Thread(() =>
{
using (var ms = new MemoryStream())
{
// The screenshot object contains a 640x480
// screenshot
var bitmap = new HtmlToBitmapConverter()
.Render(uri,
new Size(640, 480));
bitmap.Save(ms, ImageFormat.Jpeg);
screenshot = ms.ToArray();
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
// Here we have the JPEG encoded bytes of the image - we can
// just save them to a file like so...
using (var f = File.Create(#"c:\google.jpg"))
{
f.Write(screenshot, 0, screenshot.Length);
}
}
There you go - c:\google.jpg will have a screenshot of Google in it.

Caching Files in the Browser

By using the below function I am caching js, css file in the browser.
Like wise I want to cahe the Image in the browser.
private static void CacheOrFetchFromServer(string relativePath, string absolutePath, HttpContext context)
{
Cache cache = HttpRuntime.Cache;
string content;
if (cache[relativePath] == null)
{
Encoding encoding = Encoding.GetEncoding(DefaultEncodingCodePage);
CacheDependency dependency = new CacheDependency(absolutePath);
content = File.ReadAllText(absolutePath, encoding);
cache.Insert(relativePath, content, dependency);
}
else
{
content = cache[relativePath].ToString();
}
using (StreamWriter sw = new StreamWriter(context.Response.OutputStream))
{
sw.Write(content);
}
}
I had tried the below one to cache the image. But it didn't show the image.
private static void CacheOrFetchImageFileFromServer(string relativePath, string absolutePath, HttpContext context)
{
string extension = System.IO.Path.GetExtension(relativePath);
if (extension.ToUpper() == ".JPG" || extension.ToUpper() == ".PNG" || extension.ToUpper() == ".GIF" || extension.ToUpper() == ".TIFF")
{
Cache cache = HttpRuntime.Cache;
System.Drawing.Image imgPhoto = null;
if (cache[relativePath] == null)
{
Encoding encoding = Encoding.GetEncoding(DefaultEncodingCodePage);
CacheDependency dependency = new CacheDependency(absolutePath);
FileStream fs = File.OpenRead(absolutePath);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
MemoryStream ms = new MemoryStream(data);
Bitmap bmp = new Bitmap(ms);
imgPhoto = System.Drawing.Image.FromFile(absolutePath);
cache.Insert(relativePath, bmp, dependency);
}
else
{
imgPhoto = (Image) cache[relativePath];
}
context.Response.Write(absolutePath);
//using (StreamWriter sw = new StreamWriter(context.Response.OutputStream))
//{
// sw.Write(absolutePath);
//}
}
}
I'm not sure I understand what you're doing here.
First of all, the Cache object in asp.net is used to cache data on the server side, not on the client side (browser).
Caching of files, specially css, JavaScript and images, is done by the browser automatically, you don't have to do this manually for every file. And even if you had to do this manually, this isn't the way - it looks like you're just creating a copy of the file on the server's cache (I havn't done tests, but I trust Microsoft and assume this is already done in some way, and your way is actually slower).
If you want greater control over client side caching, you can enable content expiration on the IIS.

Resources