Creating an image from a URL.

This example shows how you can download and create an Image based on a URL.

Option Strict On
Option Explicit On

Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Net Imports System.IO
Public Class WinApp Inherits System.Windows.Forms.Form
<STAThread()> _ Shared Sub Main Application.Run(new WinApp()) End Sub
Dim m_pb As PictureBox
Public Sub New Me.Text = "This is my form"
m_pb = new PictureBox() m_pb.Location = new Point(0,0) m_pb.Image = GetURL("http://radio.weblogs.com/0110109/images/dotnet.gif") m_pb.Size = m_pb.Image.Size Me.ClientSize = m_pb.Image.Size
Me.Controls.add(m_pb) End Sub
Private Function GetURL(url as String) As Bitmap Dim wc As WebClient = new WebClient() Dim strm As Stream = wc.OpenRead(url) Dim bmp As BitMap = new Bitmap(strm)
strm.Close() Return bmp End Function
End Class

5 Comments

  • Do you know of any way of returning the server response eg 404 when the URL is incorrect or can we test for this before attempting to open the stream.

  • Sure. Catch the &quot;WebException&quot; exception. The &quot;Response&quot; object on that request can be cast to an HttpWebResponse object which contains a Status code indicating the web response (404, 403, etc...).



    Assuming &quot;ex&quot; is your WebException:



    Dim httpResp As HttpWebResponse = DirectCast(ex.Response, HttpWebResponse)

    If httpResp.StatusCode = HttpStatusCode.NotFound Then

    MessageBox.Show(&quot;404!&quot;, Me.Text)

    End If



  • Thats great, it worked a treat! I was trying to retreive the status code from the exception and didn't think about casting.



    I've spent serveral days getting nowhere (until now).



    There are very little resources detailing the WebClient class so your help was very much apreciated.



    Again, many thanks.

  • Any idea how to create an image of the entire page, eg. a snapshot image of cnn.com?

  • Can you do this with regular web pages, not just remote images?



    Thanks for any and all help!



    Chad

Comments have been disabled for this content.