Posts tagged ‘image’

Image from URL in C#

Here is how you can retrieve a image from a webserver. You only need to know the specific URL, the function does the rest and returns Image object.

// Get image from the given Url
// returns the image or null if not found
public static Image getUrlImage(string psUrl)
{
    WebResponse result = null;
    Image rImage = null;
   
    try
    {
        WebRequest request = WebRequest.Create(psUrl);
        byte[] rBytes;

        // Get the content
        result = request.GetResponse();
        Stream rStream = result.GetResponseStream();

        // Bytes from address
        using( BinaryReader br = new BinaryReader(rStream))
        {
            // Ask for bytes bigger than the actual stream
            rBytes = br.ReadBytes(1000000);
            br.Close();
        }
        // close down the web response object
        result.Close();

        // Bytes into image
        using( MemoryStream imageStream = new MemoryStream(rBytes, 0, rBytes.Length))
        {
            imageStream.Write(rBytes, 0, rBytes.Length);
            rImage = Image.FromStream(imageStream, true);
            imageStream.Close();
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine( “error=” + ex );
    }
    finally
    {
        if (result != null) result.Close();
    }

    return rImage;
}