AmazonScrape.Scraper.DownloadWebImage C# (CSharp) Method

DownloadWebImage() public static method

public static DownloadWebImage ( Uri url ) : BitmapImage
url System.Uri
return System.Windows.Media.Imaging.BitmapImage
        public static BitmapImage DownloadWebImage(Uri url)
        {
            // TODO: this method needs to gracefully handle unresolvable URLs and connection time-outs
            BitmapImage bitmap = new BitmapImage(url,
                new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable));

            // To make the BitmapImages thread-safe for the BackgroundWorker, they need to
            // be frozen (bitmap.Freeze()), but they shouldn't be frozen until they're done downloading.
            // We have to force the UI thread to wait until the image is downloaded so we can freeze it.
            // Otherwise, we get images in the grid that are partially-downloaded.

            // TODO: this is poor design, but after much searching, there may not be a better solution.
            //  according to MSDN, DispatcherFrames can be implemented for
            //  "Short running, very specific frames that exit when an important criteria is met."
            while (bitmap.IsDownloading) { DoEvents(); };
            bitmap.Freeze(); // Bitmap is now thread-safe and can be operated on by the backgroundworker
            return bitmap;
        }

Usage Example

Example #1
0
        /// <summary>
        /// Parses out the URL to the product's image thumbnail (if one exists)
        // and then calls DownloadWebImage to return a BitmapImage
        /// </summary>
        /// <param name="itemHtml"></param>
        /// <returns></returns>
        public static BitmapImage GetImageThumbnail(string itemHtml)
        {
            // TODO: does Amazon use a standardized image format?
            //   For now, allowing for multiple possible formats.
            string imageURLPattern = @"(http(s?):/)(/[^/]+)+\.(?:jpg|gif|png)";

            string match = GetSingleRegExMatch(itemHtml, imageURLPattern);

            if (match.Length == 0)
            {
                return(null);
            }

            if (Uri.IsWellFormedUriString(match, UriKind.Absolute))
            {
                Uri imageURL = new Uri(match);
                return(Scraper.DownloadWebImage(imageURL));
            }
            else
            {
                return(null);
            }
        }