예제 #1
0
        private string GetImageName(string url, BingImageResolution res)
        {
            string name = string.Empty;

            // URL is in this format /fd/hpk2/DiskoBay_EN-US1415620951.jpg
            // Extract the image number
            // 해상도에 따른 뒤에 넘버는 다를 수 있으니 참고할것.
            //Regex reg = new Regex(@"[0-9]+\w");
            //Match m = reg.Match(url);
            // Should now have 1415620951 from above example
            // Create path to save image to
            //if (bingimageResolution == BingImageResolution.DEFAULT)
            //{
            //    name = string.Format(@"{0}", m.Value);
            //}
            //else
            //{
            //    name = string.Format(@"{0}.jpg", m.Value);
            //}

            name = url.Substring(url.LastIndexOf('/') + 1);
            name = string.Format("{0}_{1}.jpg", name.Substring(0, name.IndexOf('_')), BingImageResolutionString[(int)res]);

            return(name);
        }
예제 #2
0
        /// <summary>
        /// Download images from Bing
        /// </summary>
        public async Task DownloadImages(StorageFolder folder = null, BingImageResolution res = BingImageResolution.PHONE_WVGA)
        {
            folder              = folder ?? ApplicationData.Current.LocalFolder;
            _folder             = folder;
            bingimageResolution = res;

            // Make sure destination folder exists
            ValidateDownloadPath();

            XDocument doc = null;

            // Because each market can have different images cycle through each of them
            foreach (string market in Markets)
            {
                // Form the URL based on market Since this will be run once per day only 1 image needs to be downloaded
                string url = string.Format(IMG_URL, NUMBER_OF_IMAGES, market);

                try
                {
                    WebClient client = new WebClient();
                    string    data   = await client.DownloadStringTask(new Uri(url));

                    doc = XDocument.Parse(data);

                    // Iterate through the image elements
                    foreach (XElement image in doc.Descendants("image"))
                    {
                        if (bingimageResolution == BingImageResolution.DEFAULT)
                        {
                            //기본사이즈인 958x512사이즈의 경우, urlBase가 아닌 그냥 url값을 사용하면 된다.
                            await SaveImage(image.Element("url").Value, res, folder);
                        }
                        else
                        {
                            string urlExt = string.Format("{0}_{1}{2}", image.Element("urlBase").Value, BingImageResolutionString[(int)bingimageResolution], BINGIMG_FORMAT);

                            if (!string.IsNullOrEmpty(urlExt))
                            {
                                await SaveImage(urlExt, res, folder);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string message = ex.Message;
                    HttpResponseError = ERRORMSG + ":" + message;

                    isDataLoaded = false;
                }
            }
        }
        /// <summary>
        /// Gets the Bing Image of The Day
        /// </summary>
        /// <param name="resolution">Sets the resolution of the image. The default is Unspecified, which usually returns 1366x768.</param>
        /// <param name="market">Sets the market to retrieve that image of the day. The default is Worldwide ("ww")</param>
        /// <returns>Image URL</returns>
        public async Task <string> GetBingImageOfTheDayAsync(BingImageResolution resolution = BingImageResolution.Unspecified, string market = "en-ww")
        {
            var request = new Uri($"http://www.bing.com/hpimagearchive.aspx?n=1&mkt={market}");

            var result = await client.GetStringAsync(request);

            var targetElement = resolution == BingImageResolution.Unspecified ? "url" : "urlBase";

            var pathString = XDocument.Parse(result).Descendants(targetElement).First().Value;

            var resolutionString = resolution == BingImageResolution.Unspecified ? "" : $"{resolution}.jpg";

            return($"http://www.bing.com{pathString}{resolutionString}");
        }
예제 #4
0
        private async Task SaveImage(string url, BingImageResolution res, StorageFolder folder = null)
        {
            try
            {
                folder = folder ?? ApplicationData.Current.LocalFolder;

                string filename = GetImageName(url, res);
                var    file     = await folder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists);

                string imageURL = BING_ROOT + url;

                WebClient client = new WebClient();

                using (Stream stream = await client.OpenReadTask(new Uri(imageURL)))
                {
                    if (stream.CanRead)
                    {
                        byte[] img = new byte[stream.Length];
                        stream.Read(img, 0, (int)stream.Length);

                        if (img.Length > 0)
                        {
                            using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                using (var outStream = fs.GetOutputStreamAt(0))
                                {
                                    using (var dataWriter = new DataWriter(outStream))
                                    {
                                        dataWriter.WriteBytes(img);

                                        await dataWriter.StoreAsync();

                                        dataWriter.DetachStream();
                                    }

                                    await outStream.FlushAsync();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //이미 다운받은 이미지를 다시 다운로드 하지 않기 위해
                //파일 생성 옵션을 CreationCollisionOption.FailIfExists로 설정했기 때문에 존재할 경우 Exception 처리.
                string msg = ex.Message;
            }
        }
예제 #5
0
        public async Task <string> GetTodayPath(BingImageResolution res = BingImageResolution.PHONE_WVGA, string market = "en-US")
        {
            string path = string.Empty;

            bingimageResolution = res;

            // Make sure destination folder exists
            ValidateDownloadPath();

            XDocument doc = null;

            // Form the URL based on market Since this will be run once per day only 1 image needs to be downloaded
            string url = string.Format(IMG_URL, NUMBER_OF_IMAGES, market);

            try
            {
                WebClient client = new WebClient();
                string    data   = await client.DownloadStringTask(new Uri(url));

                doc = XDocument.Parse(data);

                // Iterate through the image elements
                foreach (XElement image in doc.Descendants("image"))
                {
                    //_copyright = image.Element("copyright").Value;

                    string imageUrl = string.Empty;

                    if (bingimageResolution == BingImageResolution.DEFAULT)
                    {
                        //기본사이즈인 958x512사이즈의 경우, urlBase가 아닌 그냥 url값을 사용하면 된다.
                        imageUrl = image.Element("url").Value;
                    }
                    else
                    {
                        imageUrl = string.Format("{0}_{1}{2}", image.Element("urlBase").Value, BingImageResolutionString[(int)bingimageResolution], BINGIMG_FORMAT);
                    }

                    path = BING_ROOT + "/" + imageUrl;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }

            return(path);
        }
예제 #6
0
        public async Task <BingUnit> GetTodayBingUnit(BingImageResolution res = BingImageResolution.PHONE_WVGA, string market = "en-US", double networkTimeout = 7)
        {
            BingUnit unit = new BingUnit();

            bingimageResolution = res;

            XDocument doc = null;

            // Form the URL based on market Since this will be run once per day only 1 image needs to be downloaded
            string url = string.Format(IMG_URL, NUMBER_OF_IMAGES, market);

            HttpClient client = new HttpClient();

            try
            {
#if true
                client.Timeout = TimeSpan.FromSeconds(networkTimeout);
                string data = await client.GetStringAsync(new Uri(url));
#else
                WebClient client = new WebClient();
                string    data   = await client.DownloadStringTask(new Uri(url));
#endif

                doc = XDocument.Parse(data);

                // Iterate through the image elements
                foreach (XElement image in doc.Descendants("image"))
                {
                    unit.Copyright = GetElmentValue(image, "copyright");
                    unit.StartDate = GetElmentValue(image, "startdate");
                    unit.EndDate   = GetElmentValue(image, "enddate");

                    string imageUrl = string.Empty;

                    if (bingimageResolution == BingImageResolution.DEFAULT)
                    {
                        //기본사이즈인 958x512사이즈의 경우, urlBase가 아닌 그냥 url값을 사용하면 된다.
                        imageUrl = GetElmentValue(image, "url");
                    }
                    else
                    {
                        imageUrl = string.Format("{0}_{1}{2}", image.Element("urlBase").Value, BingImageResolutionString[(int)bingimageResolution], BINGIMG_FORMAT);
                    }

                    unit.Path = BING_ROOT + imageUrl;

                    bool bSearched = false;
                    foreach (XElement hotspots in image.Descendants("hotspots"))
                    {
                        foreach (XElement hotspot in hotspots.Descendants("hotspot"))
                        {
                            string strLink = hotspot.Element("link").Value;
                            if (strLink.Contains("maps"))
                            {
                                //unit.MapLink = ReplaceMapLevel(strLink, "4");
                                unit.MapLink = strLink;
                                bSearched    = true;
                                break;
                            }
                        }

                        if (bSearched)
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                client.CancelPendingRequests();
                client.Dispose();
                string message = ex.Message;
                return(null);
            }

            return(unit);
        }
예제 #7
0
        public async Task DownloadTodayImage(StorageFolder folder = null, BingImageResolution res = BingImageResolution.PHONE_WVGA, string market = "en-US")
        {
            folder              = folder ?? ApplicationData.Current.LocalFolder;
            _folder             = folder;
            bingimageResolution = res;

            // Make sure destination folder exists
            ValidateDownloadPath();

            XDocument doc = null;

            // Form the URL based on market Since this will be run once per day only 1 image needs to be downloaded
            string url = string.Format(IMG_URL, NUMBER_OF_IMAGES, market);

            try
            {
                WebClient client = new WebClient();
                string    data   = await client.DownloadStringTask(new Uri(url));

                doc = XDocument.Parse(data);

                // Iterate through the image elements
                foreach (XElement image in doc.Descendants("image"))
                {
                    //_copyright = image.Element("copyright").Value;

                    string imageUrl = string.Empty;

                    if (bingimageResolution == BingImageResolution.DEFAULT)
                    {
                        //기본사이즈인 958x512사이즈의 경우, urlBase가 아닌 그냥 url값을 사용하면 된다.
                        imageUrl = image.Element("url").Value;
                    }
                    else
                    {
                        imageUrl = string.Format("{0}_{1}{2}", image.Element("urlBase").Value, BingImageResolutionString[(int)bingimageResolution], BINGIMG_FORMAT);
                    }

                    string beforeImageUrl = await ReadFile("ImageUrl.txt");

                    if (beforeImageUrl.Equals(imageUrl))
                    {
                        if (OnUpdated != null)
                        {
                            OnUpdated(this, new EventArgs());
                        }

                        return;
                    }

                    if (!string.IsNullOrEmpty(imageUrl))
                    {
                        await SaveImage(imageUrl, image.Element("fullstartdate").Value, folder);

                        await WriteFile("ImageUrl.txt", imageUrl, CreationCollisionOption.ReplaceExisting);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                HttpResponseError = ERRORMSG + ":" + message;

                isDataLoaded = false;
            }
        }