Attempts to download a bitmap from a given URI, then loads the bitmap into a Bitmap object and returns. Obviously there are numerous failure cases for a function like this. For ease of use, all errors will be reported in a catch-all BitmapManipException, which provides a textual error message based on the exception that occurs. As usual, the underlying exception is available in InnerException property. - CSharp System.Drawing

CSharp examples for System.Drawing:Bitmap

Description

Attempts to download a bitmap from a given URI, then loads the bitmap into a Bitmap object and returns. Obviously there are numerous failure cases for a function like this. For ease of use, all errors will be reported in a catch-all BitmapManipException, which provides a textual error message based on the exception that occurs. As usual, the underlying exception is available in InnerException property.

Demo Code


using System.Net;
using System.IO;/*from ww  w  .  j av a  2s. c  o m*/
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing;
using System;

public class Main{
        /// <summary>Attempts to download a bitmap from a given URI, then loads the bitmap into
      /// a <code>Bitmap</code> object and returns.
      /// 
      /// Obviously there are numerous failure cases for a function like this.  For ease
      /// of use, all errors will be reported in a catch-all <code>BitmapManipException</code>,
      /// which provides a textual error message based on the exception that occurs.  As usual,
      /// the underlying exception is available in <code>InnerException</code> property.
      /// </summary>
      /// 
      /// <param name="uri"><code>Uri</code> object specifying the URI from which to retrieve image</param>
      /// <param name="timeoutMs">Timeout (in milliseconds) to wait for response</param>
      /// 
      /// <returns>Bitmap object from URI.  Shouldn't ever be null, as any error will be reported
      ///     in an exception.</returns>
      public static Bitmap GetBitmapFromUri(Uri uri, int timeoutMs) {
         Bitmap downloadedImage = null;

         //Create a web request object for the URI, retrieve the contents,
         //then feed the results into a new Bitmap object.  Note that we 
         //are particularly sensitive to timeouts, since this all must happen
         //while the user waits
         try {
            WebRequest req = WebRequest.Create(uri);
            req.Timeout = timeoutMs;

            //The GetResponse call actually makes the request
            WebResponse resp = req.GetResponse();

            //Check the content type of the response to make sure it is
            //one of the formats we support
            if (Array.IndexOf(BitmapManipulator.supportedMimeTypes, 
                          resp.ContentType) == -1) {
               String contentType = resp.ContentType;
               resp.Close();
               throw new BitmapManipException(String.Format("The image at the URL you provided is in an unsupported format ({0}).  Uploaded images must be in either JPEG, GIF, BMP, TIFF, PNG, or WMF formats.",
                                                 contentType),
                                       new NotSupportedException(String.Format("MIME type '{0}' is not a recognized image type", contentType)));
            }

            //Otherwise, looks fine
            downloadedImage = new Bitmap(resp.GetResponseStream());

            resp.Close();

            return downloadedImage;
         } catch (UriFormatException exp) {
            throw new BitmapManipException("The URL you entered is not valid.  Please enter a valid URL, of the form http://servername.com/folder/image.gif",
                                    exp);
         } catch (WebException exp) {
            //Some sort of problem w/ the web request
            String errorDescription;

            if (exp.Status == WebExceptionStatus.ConnectFailure) {
               errorDescription = "Connect failure";
            } else if (exp.Status == WebExceptionStatus.ConnectionClosed) {
               errorDescription = "Connection closed prematurely";
            } else if (exp.Status == WebExceptionStatus.KeepAliveFailure) {
               errorDescription = "Connection closed in spite of keep-alives";
            } else if (exp.Status == WebExceptionStatus.NameResolutionFailure) {
               errorDescription = "Unable to resolve server name.  Double-check the URL for errors";
            } else if (exp.Status == WebExceptionStatus.ProtocolError) {
               errorDescription = "Protocol-level error.  The server may have reported an error like 404 (file not found) or 403 (access denied), or some other similar error";
            } else if (exp.Status == WebExceptionStatus.ReceiveFailure) {
               errorDescription = "The server did not send a complete response";
            } else if (exp.Status == WebExceptionStatus.SendFailure) {
               errorDescription = "The complete request could not be sent to the server";
            } else if (exp.Status == WebExceptionStatus.ServerProtocolViolation) {
               errorDescription = "The server response was not a valid HTTP response";
            } else if (exp.Status == WebExceptionStatus.Timeout) {
               errorDescription = "The server did not respond quickly enough.  The server may be down or overloaded.  Try again later";
            } else {
               errorDescription = exp.Status.ToString();
            }

            throw new BitmapManipException(String.Format("An error occurred while communicating with the server at the URL you provided.  {0}.", 
                                              errorDescription),
                                    exp);
         } catch (BitmapManipException exp) {
            //Don't modify this one; pass it along
            throw exp;
         } catch (Exception exp) {
            throw new BitmapManipException(String.Format("An error ocurred while retrieving the image from the URL you provided: {0}",
                                              exp.Message),
                                    exp);
         }
      }
        /// <summary>Attempts to download a bitmap from a given URI, then loads the bitmap into
      /// a <code>Bitmap</code> object and returns.
      /// 
      /// Obviously there are numerous failure cases for a function like this.  For ease 
      /// of use, all errors will be reported in a catch-all <code>BitmapManipException</code>,
      /// which provides a textual error message based on the exception that occurs.  As usual,
      /// the underlying exception is available in <code>InnerException</code> property.
      /// </summary>
      /// 
      /// <param name="uri">String containing URI from which to retrieve image</param>
      /// <param name="timeoutMs">Timeout (in milliseconds) to wait for response</param>
      /// 
      /// <returns>Bitmap object from URI.  Shouldn't ever be null, as any error will be reported
      ///     in an exception.</returns>
      public static Bitmap GetBitmapFromUri(String uri, int timeoutMs) {
         //Convert String to URI
         try {
            Uri uriObj = new Uri(uri);

            return GetBitmapFromUri(uriObj, timeoutMs);
         } catch (ArgumentNullException ex) {
            throw new BitmapManipException("Parameter 'uri' is null", ex);
         } catch (UriFormatException ex) {
            throw new BitmapManipException(String.Format("Parameter 'uri' is malformed: {0}", ex.Message),
                                    ex);
         }
      }
        /// <summary>Attempts to download a bitmap from a given URI, then loads the bitmap into
      /// a <code>Bitmap</code> object and returns.
      /// 
      /// Obviously there are numerous failure cases for a function like this.  For ease
      /// of use, all errors will be reported in a catch-all <code>BitmapManipException</code>,
      /// which provides a textual error message based on the exception that occurs.  As usual,
      /// the underlying exception is available in <code>InnerException</code> property.
      /// 
      /// Times out after 10 seconds waiting for a response from the server.</summary>
      /// 
      /// <param name="uri"><code>Uri</code> object specifying the URI from which to retrieve image</param>
      /// 
      /// <returns>Bitmap object from URI.  Shouldn't ever be null, as any error will be reported
      ///     in an exception.</returns>
      public static Bitmap GetBitmapFromUri(Uri uri) {
         return GetBitmapFromUri(uri, 10*1000);
      }
        /// <summary>Attempts to download a bitmap from a given URI, then loads the bitmap into
      /// a <code>Bitmap</code> object and returns.
      /// 
      /// Obviously there are numerous failure cases for a function like this.  For ease 
      /// of use, all errors will be reported in a catch-all <code>BitmapManipException</code>,
      /// which provides a textual error message based on the exception that occurs.  As usual,
      /// the underlying exception is available in <code>InnerException</code> property.
      /// 
      /// Times out after 10 seconds waiting for a response from the server.</summary>
      /// 
      /// <param name="uri">String containing URI from which to retrieve image</param>
      /// 
      /// <returns>Bitmap object from URI.  Shouldn't ever be null, as any error will be reported
      ///     in an exception.</returns>
      public static Bitmap GetBitmapFromUri(String uri) {
         //Convert String to URI
         try {
            Uri uriObj = new Uri(uri);

            return GetBitmapFromUri(uriObj);
         } catch (ArgumentNullException ex) {
            throw new BitmapManipException("Parameter 'uri' is null", ex);
         } catch (UriFormatException ex) {
            throw new BitmapManipException(String.Format("Parameter 'uri' is malformed: {0}", ex.Message),
                                    ex);
         }
      }
}

Related Tutorials