public void SetXmlToAlbum(Stream stream, ChameleonAlbum album, string thumbSizePostfix, string fullSizePostfix, Size thumbSize) { // Load the stream into and XDocument for processing XDocument doc = XDocument.Load(stream); // Iterate through the image elements foreach (XElement image in doc.Descendants("image")) { string imgUrl = image.Element("url").Value; imgUrl = imgUrl.Replace(image.Element("urlBase").Value + "_", "").Replace(".jpg", ""); string thumbailImg = image.Element("urlBase").Value + thumbSizePostfix; string verticalImg = image.Element("urlBase").Value + fullSizePostfix; album.Add(new WebPicture() { Guid = Guid.NewGuid(), SourceOrigin = SourceOrigin.BingToday, FileName = FileHelper.GetFileName(verticalImg), Name = image.Element("copyright").Value, Path = BING + verticalImg, Width = (int)ResolutionHelper.CurrentResolution.Width, Height = (int)ResolutionHelper.CurrentResolution.Height, ContentType = "image/jpeg", Thumbnail = new WebPicture() { Path = BING + thumbailImg, Width = (int)thumbSize.Width, Height = (int)thumbSize.Height, ContentType = "image/jpeg", } }); } }
public async void Load() { ChameleonAlbum album = new ChameleonAlbum(); using (HttpClient httpClient = new HttpClient()) { using (var picResponse = await httpClient.GetAsync("http://www.nasa.gov/rss/dyn/image_of_the_day.rss", HttpCompletionOption.ResponseContentRead)) { if (picResponse.IsSuccessStatusCode) { if (picResponse.Content.Headers.ContentEncoding.Contains("gzip")) { using (GZipInputStream gzip = new GZipInputStream(await picResponse.Content.ReadAsStreamAsync())) { SetXmlToAlbum(gzip, album); } } else { using (Stream stream = await picResponse.Content.ReadAsStreamAsync()) { SetXmlToAlbum(stream, album); } } } } using (var picResponse = await httpClient.GetAsync("http://www.nasa.gov/rss/dyn/chandra_images.rss", HttpCompletionOption.ResponseContentRead)) { if (picResponse.IsSuccessStatusCode) { if (picResponse.Content.Headers.ContentEncoding.Contains("gzip")) { using (GZipInputStream gzip = new GZipInputStream(await picResponse.Content.ReadAsStreamAsync())) { SetXmlToAlbum(gzip, album); } } else { using (Stream stream = await picResponse.Content.ReadAsStreamAsync()) { SetXmlToAlbum(stream, album); } } } } } if (LoadCompleted != null) { LoadCompleted(this, new TodayImageResult() { Album = album }); } }
private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e) { String pivotName = (e.AddedItems[0] as PivotItem).Name; ApplicationBar.IsVisible = false; LongListMultiSelector selector = GetSelectorByPivotName(pivotName); if (selector != PhonePictureSelector) { ApplicationBar.IsVisible = true; ChameleonAlbum album = selector.ItemsSource as ChameleonAlbum; ChangeAppbarIconButton(selector, 0, true); (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = (album != null && album.Count > 0); } }
private void finder_FindCompleted(object sender, ChameleonAlbum webAlbum) { Deployment.Current.Dispatcher.BeginInvoke(() => { SearchingProgressBar.Visibility = System.Windows.Visibility.Collapsed; WebPictureSelector.ItemsSource = webAlbum; (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = webAlbum.Count > 0; if (webAlbum.Count > 0) { TxtSearchBingNoData.Visibility = System.Windows.Visibility.Collapsed; } else { TxtSearchBingNoData.Visibility = System.Windows.Visibility.Visible; } }); }
void bgPhoneLoader_ProgressChanged(object sender, ProgressChangedEventArgs e) { object[] args = e.UserState as object[]; ChameleonAlbum phoneAlbum = args[0] as ChameleonAlbum; Picture picture = args[1] as Picture; using (Stream stream = picture.GetImage()) { WriteableBitmap bitmap = JpegHelper.Resize(stream, new Size(200, 200), true); phoneAlbum.Add(new PhonePicture() { SourceOrigin = SourceOrigin.Phone, AlbumName = picture.Album.Name, ImageSource = bitmap, Name = picture.Name }); } }
private void SetXmlToAlbum(Stream stream, ChameleonAlbum album) { try { // Load the stream into and XDocument for processing XDocument doc = XDocument.Load(stream); // Iterate through the image elements foreach (XElement image in doc.Descendants("item")) { string imgUrl = image.Element("enclosure").Attribute("url").Value; long length = long.Parse(image.Element("enclosure").Attribute("length").Value); string type = image.Element("enclosure").Attribute("type").Value; string thumbailImg = IMG_URL + "226x170/public/"; string orgImg = IMG_URL + "946xvariable_height/public/"; string fileName = imgUrl.Substring(imgUrl.LastIndexOf("/") + 1); album.Add(new WebPicture() { Guid = Guid.NewGuid(), SourceOrigin = SourceOrigin.NasaToday, FileName = FileHelper.GetFileName(fileName.Substring(0, fileName.LastIndexOf("?"))), Name = image.Element("title").Value, Path = orgImg + fileName, FileSize = length, Width = 946, //Height = (int)resolution.Height, ContentType = type, Thumbnail = new WebPicture() { Path = thumbailImg + fileName, Width = 226, Height = 170, ContentType = type, } }); } } catch (System.Xml.XmlException xe) { System.Diagnostics.Debug.WriteLine(xe.Message); } }
// Handle the query callback. private void _onImageQueryComplete(IAsyncResult imageResults) { //_clientDone.Set(); // Get the original query from the imageResults. DataServiceQuery <Bing.ImageResult> query = imageResults.AsyncState as DataServiceQuery <Bing.ImageResult>; ChameleonAlbum webAlbum = new ChameleonAlbum(); try { foreach (var result in query.EndExecute(imageResults)) { webAlbum.Add(new WebPicture() { Guid = Guid.NewGuid(), SourceOrigin = SourceOrigin.Search, Name = result.Title, Path = result.MediaUrl, Width = (int)result.Width, Height = (int)result.Height, FileSize = (long)result.FileSize, ContentType = result.ContentType, Thumbnail = new WebPicture() { Path = result.Thumbnail.MediaUrl, Width = (int)result.Thumbnail.Width, Height = (int)result.Thumbnail.Height, FileSize = (long)result.Thumbnail.FileSize, ContentType = result.Thumbnail.ContentType } }); } } catch (Exception e) { if (e.InnerException.Message == "NotFound") { //검색된 데이터 없음. } } FindCompleted(this, webAlbum); }
void nasaToday_LoadCompleted(object sender, TodayImageResult result) { Deployment.Current.Dispatcher.BeginInvoke(() => { ChameleonAlbum album = new ChameleonAlbum(); NasaTodayPictureSelector.ItemsSource = album; foreach (var pic in result.Album) { album.Add(pic); } if (result.Index > 0) { (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = result.Album.Count > 0; } NasaTodayProgressBar.Visibility = System.Windows.Visibility.Collapsed; }); }
void bingToday_LoadCompleted(object sender, TodayImageResult result) { Deployment.Current.Dispatcher.BeginInvoke(() => { ChameleonAlbum album = BingTodayPictureSelector.ItemsSource as ChameleonAlbum; if (album == null) { album = new ChameleonAlbum(); BingTodayPictureSelector.ItemsSource = album; } bool loadBreak = false; foreach (var pic in result.Album) { bool exists = album.Any(x => { return(((WebPicture)x).Path == ((WebPicture)pic).Path); }); if (!exists) { album.Add(pic); } else { loadBreak = true; } } if (!loadBreak) { bingToday.Load(result.Index); } if (result.Index > 0) { (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = result.Album.Count > 0; } BingTodayProgressBar.Visibility = System.Windows.Visibility.Collapsed; }); }
public static void ProcessDownloadImageResult(ObservableCollection <DownloadItem> downloadList, LongListMultiSelector selector) { ChameleonAlbum album = selector.ItemsSource as ChameleonAlbum; //저장소에서 리턴값 삭제 PhoneApplicationService.Current.State.Remove(Constants.DOWNLOAD_IMAGE_LIST); foreach (DownloadItem item in downloadList) { AbstractPicture pic = album.First(x => x.Guid == item.Guid) as AbstractPicture; if (pic.Guid == item.Guid) { if (item.DownloadStatusCode == DownloadStatus.Completed) { //1. 해당 파일이 정상적으로 완료된 파일이라면 화면에서 삭제 처리 album.Remove(pic); } else if (item.DownloadStatusCode == DownloadStatus.DownloadFailed || item.DownloadStatusCode == DownloadStatus.SaveFailed) { //2. 해당 파일이 실패한 경우 이면 if (item.BlackListMode == BlackListMode.Domain) { //2.1 블랙리스트에 추가된 파일이라면 삭제 album.Remove(pic); } else { //2.2 아니면 실패 뱃지를 달아준다. 실패 원인을 표시한다. pic.ProgressStatus = item.DownloadStatus.Replace(AppResources.MsgAddDomainFilter, string.Empty); } } } } //3. 선택 모드 해제 (여기서 즉시하면 에러가 발생하므로 딜레이 0.5초를 줘서 실행시킴) Deployment.Current.Dispatcher.BeginInvoke(async() => { await Task.Delay(500); selector.EnforceIsSelectionEnabled = false; }); }
void bgPhoneLoader_DoWork(object sender, DoWorkEventArgs e) { ChameleonAlbum phoneAlbum = e.Argument as ChameleonAlbum; BackgroundWorker worker = sender as BackgroundWorker; using (MediaLibrary mediaLibrary = new MediaLibrary()) { foreach (var pa in mediaLibrary.RootPictureAlbum.Albums) { if (pa.Pictures.Count > 0) { var pic = (from picture in pa.Pictures orderby picture.Date descending select picture).First(); worker.ReportProgress(0, new object[] { phoneAlbum, pic }); //System.Threading.Thread.Sleep(50); } } } }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.NavigationMode == NavigationMode.New) { ChameleonAlbum album = new ChameleonAlbum(); PhonePictureSelector.ItemsSource = album; bgPhoneLoader.RunWorkerAsync(album); bgBingLoader.RunWorkerAsync(); bgNasaLoader.RunWorkerAsync(); LoadWebPictureAlbum(); } else if (e.NavigationMode == NavigationMode.Back) { if (PhoneApplicationService.Current.State.ContainsKey(Constants.DOWNLOAD_IMAGE_LIST)) { ObservableCollection <DownloadItem> downloadList = PhoneApplicationService.Current.State[Constants.DOWNLOAD_IMAGE_LIST] as ObservableCollection <DownloadItem>; PageHelper.ProcessDownloadImageResult(downloadList, GetSelectorBySourceOrigin(downloadList[0].SourceOrigin)); } } }
//락스크린 리스트 로딩 public void LoadLockscreenList() { //락스크린 썸네일 이미지 크기 설정 LockscreenSelector.GridCellSize = LockscreenHelper.ThumnailSize; ChameleonAlbum phoneAlbum = LockscreenSelector.ItemsSource as ChameleonAlbum; if (phoneAlbum == null) { phoneAlbum = new ChameleonAlbum(); LockscreenSelector.ItemsSource = phoneAlbum; } using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { var imgNames = from element in isoStore.GetFileNames() where element.Contains(Constants.LOCKSCREEN_IMAGE_POSTFIX) orderby element.Substring(0, element.IndexOf("_")) ascending select element; Uri lockscreenFileUri = null; try { lockscreenFileUri = LockScreen.GetImageUri(); } catch (Exception) { } string lockscreenFileName = null; if (lockscreenFileUri != null) { lockscreenFileName = lockscreenFileUri.ToString() .Replace(Constants.PREFIX_APP_DATA_FOLDER, string.Empty) .Replace(Constants.LOCKSCREEN_IMAGE_A_POSTFIX, Constants.LOCKSCREEN_IMAGE_POSTFIX) .Replace(Constants.LOCKSCREEN_IMAGE_B_POSTFIX, Constants.LOCKSCREEN_IMAGE_POSTFIX); } foreach (string imgName in imgNames) { bool isReady = isoStore.GetFileNames(imgName.Replace(Constants.LOCKSCREEN_IMAGE_POSTFIX, Constants.LOCKSCREEN_IMAGE_READY_POSTFIX)).Any(); var pic = from element in phoneAlbum where element.Name == imgName select element; if (pic.Any()) { //원래 존재하는 이름이므로 해당 파일에 대한 정보를 업데이트 처리 PhonePicture curPic = pic.First() as PhonePicture; if (curPic.Name == lockscreenFileName) { curPic.CurrentLockscreen = currentLockscreenUri; curPic.Margin = currentLockscreenMargin; } else { curPic.CurrentLockscreen = null; curPic.Margin = new Thickness(); } //이미지 변경 시간을 체크해서, 이미지가 편집이 되었다면 이미지를 다시 로드 DateTimeOffset offset = isoStore.GetLastWriteTime(imgName); if (offset.Subtract(curPic.DateTimeOffset).Milliseconds != 0) { curPic.DateTimeOffset = offset; WriteableBitmap bitmap = null; string thumbName = imgName.Replace(Constants.LOCKSCREEN_IMAGE_POSTFIX, Constants.LOCKSCREEN_IMAGE_THUMNAIL_POSTFIX); string[] thumbs = isoStore.GetFileNames(thumbName); //썸네일이 없는 경우면 원본 이름을 셋팅 if (thumbs == null || thumbs.Length == 0) { thumbName = imgName; } //이미지 로드 using (IsolatedStorageFileStream sourceStream = isoStore.OpenFile(thumbName, FileMode.Open, FileAccess.Read)) { //썸네일이 없는 경우면 원본을 리사이징 if (thumbs == null || thumbs.Length == 0) { bitmap = JpegHelper.Resize(sourceStream, LockscreenHelper.ThumnailSize, true); } else { bitmap = BitmapFactory.New(0, 0).FromStream(sourceStream); } } //썸네일 이미지 교체 curPic.ThumbnailImageSource = bitmap; } //편집 페이지에서 준비상태로 편집이 완료되었으면 편집 경고 삭제 if (isReady) { curPic.Warnning = null; } } else { //존재하지 않는 파일이므로 새롭게 리스트에 추가 WriteableBitmap bitmap = null; string thumbName = imgName.Replace(Constants.LOCKSCREEN_IMAGE_POSTFIX, Constants.LOCKSCREEN_IMAGE_THUMNAIL_POSTFIX); string[] thumbs = isoStore.GetFileNames(thumbName); Uri uri = null; Thickness margin = new Thickness(); //썸네일이 없는 경우면 원본 이름을 셋팅 if (thumbs == null || thumbs.Length == 0) { thumbName = imgName; } //이미지 로드 using (IsolatedStorageFileStream sourceStream = isoStore.OpenFile(thumbName, FileMode.Open, FileAccess.Read)) { //썸네일이 없는 경우면 원본을 리사이징 if (thumbs == null || thumbs.Length == 0) { bitmap = JpegHelper.Resize(sourceStream, LockscreenHelper.ThumnailSize, true); } else { bitmap = BitmapFactory.New(0, 0).FromStream(sourceStream); } } //현재 락스크린 지정 이미지인 경우 처리 if (lockscreenFileName == imgName) { uri = currentLockscreenUri; margin = currentLockscreenMargin; } //락스크린 이미지 객체 생성 phoneAlbum.Add(new PhonePicture() { Guid = Guid.NewGuid(), Name = imgName, ThumnailName = thumbName, ThumbnailImageSource = bitmap, Margin = margin, CurrentLockscreen = uri, Warnning = isReady ? null : warnningUri, Opacity = 1, DateTimeOffset = isoStore.GetLastWriteTime(thumbName) }); } //경고 안내문구 표시 if (!LockscreenEditWarnning && !isReady) { LockscreenEditWarnning = true; } } } (IAppBarLockscreen.Buttons[0] as ApplicationBarIconButton).IsEnabled = !(phoneAlbum.Count == 0 && IAppBarLockscreen.Buttons.Count > 1); //이미지 갯수 표시 LockscreenCount = string.Format("({0})", phoneAlbum.Count); //에디팅 경고 표시 LockscreenEditWarnning = phoneAlbum.Any(x => (x as PhonePicture).Warnning != null); if (phoneAlbum.Count == 0) { //도움말 표시 토글 TxtLockscreen.Visibility = Visibility.Visible; //이미지가 없고 활성화된 라이브타일이 없으면 스케쥴러 정저 if (!ExistsActiveTile) { RemoveAgent(Constants.PERIODIC_TASK_NAME); } UseLockscreen.IsChecked = false; UseLockscreen.IsEnabled = false; } else { UseLockscreen.IsEnabled = true; TxtLockscreen.Visibility = Visibility.Collapsed; } }
public async void Load(int idx, string regionCode) { ChameleonAlbum album = new ChameleonAlbum(); int newIndex = -1; if (idx != -1) { Size resolution = ResolutionHelper.CurrentResolution; HttpClient httpClient = new HttpClient(); string url = string.Format(IMG_URL, idx, 7, regionCode); var picResponse = await httpClient.GetAsync(url, HttpCompletionOption.ResponseContentRead); string sizeFormat = "_{0:0.##}x{1:0.##}.jpg"; Size thumbSize = new Size(240, 400); Size fullSize = resolution; if (SettingHelper.GetString(Constants.BING_SEARCH_ASPECT) == "Wide") { thumbSize.Width = 400; thumbSize.Height = 240; fullSize.Width = resolution.Height; fullSize.Height = resolution.Width; } string thumbSizePostfix = string.Format(sizeFormat, thumbSize.Width, thumbSize.Height); string fullSizePostfix = string.Format(sizeFormat, fullSize.Width, fullSize.Height); if (picResponse.IsSuccessStatusCode) { try { if (picResponse.Content.Headers.ContentEncoding.Contains("gzip")) { using (GZipInputStream gzip = new GZipInputStream(await picResponse.Content.ReadAsStreamAsync())) { SetXmlToAlbum(gzip, album, thumbSizePostfix, fullSizePostfix, thumbSize); } } else { using (Stream stream = await picResponse.Content.ReadAsStreamAsync()) { SetXmlToAlbum(stream, album, thumbSizePostfix, fullSizePostfix, thumbSize); } } newIndex = idx + 7; } catch (System.Xml.XmlException xe) { System.Diagnostics.Debug.WriteLine(xe.Message); } } picResponse.Dispose(); } LoadCompleted(this, new TodayImageResult() { Album = album, Index = newIndex }); }