Capturing Remote Images Using ASPJpeg
Written by Nick Dunn published 19th Mar 2006 | Comment on this article
ASPJpeg is a fantastic way of manipulating images on the server. But what if the image is on another server completely?
Introduction
This problem reared its ugly head when developing the OpenHosting website. On the new Status page we wanted to have a graph of the current network throughput. The only problem was that the software generating this graph sits on a separate web server to the OpenHosting website. We wanted to be able to grab this image and use ASPJpeg to clean it, resize it, and most importantly, cache it.
How it's done...
Thankfully there's a simple solution to grabbing an image from a remote server. Using the XMLHTTP object (commonly used to request remote documents such as XML files) we request the PNG image file, and use ASPJpeg's OpenBinary method to read the incoming byte stream. The image is then saved as a JPEG on the web server. A simple ASP script works out whether the cached image needs updating. If so, the above routine is executed. If not, the page simply returns the cached JPEG image. Here's the (modified) code.
<%
If cacheFileIsExpired("statusgraph.jpg", 4,"hours") Then
Response.Write("<img src=""getRemoteImage.asp"" alt=""Updated image"" />")
Else
Response.Write("<img src=""cachedImage.jpg"" alt=""Image loaded from cache"" />")
End If
%>
And the getRemoteImage page that works the XMLHTTP magic:
<%
Dim objXMLHTTP : Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
Dim objJpeg : Set objJpeg = Server.CreateObject("Persits.Jpeg")
objXMLHTTP.Open "GET", "http://www.domain2.com/theImage.jpg"
objXMLHTTP.Send
objJpeg.OpenBinary(objXMLHTTP.ResponseBody)
objJpeg.Save "d:\webs\domain1.com\wwwroot\cachedImage.jpg"
objJpeg.SendBinary
Set objXMLHTTP = Nothing
Response.End
%>
Note that the "cacheFileIsExpired" function in the first code example is the same that is used in my Data caching using text files article.