public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var imageSource = value as string; if (imageSource != null) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(imageSource)) { var file = store.OpenFile(imageSource, FileMode.Open, FileAccess.Read); { var image = new ExtendedImage(); image.LoadingCompleted += (sender, args) => { var count = image.Frames.Count; }; image.LoadingFailed += (sender, args) => { }; image.SetSource(file); return(image); } } } } return(null); }
public async void LoadImage(String filename) { var file = await KnownFolders.PicturesLibrary.GetFileAsync(filename); ExtendedImage image = new ExtendedImage(); image.LoadingCompleted += (o, ea) => Dispatcher.BeginInvoke(() => { AnimatedImage.Source = image; }); image.SetSource((await file.OpenReadAsync()).AsStreamForRead()); }
public override Codec.DecodeResult Decode(Stream input) { var wait = new ManualResetEvent(false); var its = new ExtendedImage(); its.LoadingCompleted += (s, e) => wait.Set(); its.LoadingFailed += (s, e) => { Debug.WriteLine(e.ExceptionObject.ToString()); wait.Set(); }; its.SetSource(input); wait.WaitOne(); return(Decode(its)); }
/// <summary> /// Loads an image from an Url asynchronously /// </summary> /// <param name="location">The location of the image</param> /// <returns>A BitmapImage, that can be set as a source</returns> public static async Task<ExtendedImage> LoadImageFromUrlAsync(Uri location) { WebClient client = new WebClient(); ExtendedImage image = new ExtendedImage(); Stream source = await client.OpenReadTaskAsync(location); if (location.ToString().EndsWith("gif", StringComparison.InvariantCultureIgnoreCase)) { image.SetSource(source); TaskCompletionSource<ExtendedImage> imageLoaded = new TaskCompletionSource<ExtendedImage>(); EventHandler loadingCompleteHandler = new EventHandler((sender, e) => { imageLoaded.SetResult(image); }); EventHandler<UnhandledExceptionEventArgs> loadingFailedHandler = new EventHandler<UnhandledExceptionEventArgs>((sender, e) => { imageLoaded.SetResult(image); #if DEBUG if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); #endif }); image.LoadingCompleted += loadingCompleteHandler; image.LoadingFailed += loadingFailedHandler; image = await imageLoaded.Task; //Remove handlers, otherwise the object might be kept in the memory image.LoadingCompleted -= loadingCompleteHandler; image.LoadingFailed -= loadingFailedHandler; } else { BitmapImage bmp = new BitmapImage(); bmp.SetSource(source); WriteableBitmap writeable = new WriteableBitmap(bmp); image = ImageExtensions.ToImage(writeable); } source.Close(); return image; }
/// <summary> /// Modifies the source data before passing it to the target for display in the UI. /// </summary> /// <param name="value">The source data being passed to the target.</param> /// <param name="targetType">The <see cref="T:System.Type"/> of data expected by the target dependency property.</param> /// <param name="parameter">An optional parameter to be used in the converter logic.</param> /// <param name="culture">The culture of the conversion.</param> /// <returns> /// The value to be passed to the target dependency property. /// </returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { object result = DependencyProperty.UnsetValue; if (value != null) { var sourceAsUri = value as Uri; if (sourceAsUri != null) { ExtendedImage extendedImage = new ExtendedImage(); extendedImage.UriSource = sourceAsUri; return(extendedImage); } var sourceAsString = value as String; if (sourceAsString != null) { ExtendedImage extendedImage = new ExtendedImage(); extendedImage.UriSource = new Uri(sourceAsString, UriKind.RelativeOrAbsolute); return(extendedImage); } var sourceAsStream = value as Stream; if (sourceAsStream != null) { ExtendedImage extendedImage = new ExtendedImage(); extendedImage.SetSource(sourceAsStream); return(extendedImage); } var sourceAsWriteableBitmap = value as WriteableBitmap; if (sourceAsWriteableBitmap != null) { return(sourceAsWriteableBitmap.ToImage()); } var sourceAsExtendedImage = value as ExtendedImage; if (sourceAsExtendedImage != null) { return(sourceAsExtendedImage); } } return(result); }
private async void LoadGifs() { StorageFile deleteFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Images/TaskDeleteAnimation.gif", UriKind.RelativeOrAbsolute)); ExtendedImage delteImage = new ExtendedImage(); delteImage.SetSource(await deleteFile.OpenStreamForReadAsync()); this.TaskDeleteAnimation.Source = delteImage; StorageFile completeFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Images/TaskCompleteAnimation.gif", UriKind.RelativeOrAbsolute)); ExtendedImage completeImage = new ExtendedImage(); completeImage.SetSource(await completeFile.OpenStreamForReadAsync()); this.TaskCompleteAnimation.Source = completeImage; }
private void ApplyImageSource() { if (ElementImageBrush != null) { Deployment.Current.Dispatcher.BeginInvoke(() => { ElementImageBrush.Stretch = Stretch; if (Source == null) { ElementImageBrush.Stretch = Stretch.Uniform; ElementImageBrush.Source = DefaultImage; return; } #region jpeg/png try { using (var memStream = new MemoryStream(Source)) { memStream.Position = 0; var bitmapImage = new BitmapImage(); bitmapImage.SetSource(memStream); ElementImageBrush.Source = bitmapImage; } } #endregion #region others catch (Exception exception) { Debug.WriteLine("set gif image. length: {0}", Source.Length); using (var memStream = new MemoryStream(Source)) { memStream.Position = 0; var extendedImage = new ExtendedImage(); extendedImage.SetSource(memStream); extendedImage.LoadingCompleted += (o, e) => { var ei = o as ExtendedImage; ElementImageBrush.Source = ei.ToBitmap(); }; } } #endregion }); } }
/// <summary> /// Handles the Click event of the LoadImageButton control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param> private void LoadImageButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Multiselect = false; // Define the filter to load all format that can be handled by image tools. openFileDialog.Filter = "Image Files (*.jpg;*.png;*.bmp;*gif)|*.jpg;*.png;*.bmp;*.gif"; if (openFileDialog.ShowDialog() == true) { FileInfo fileInfo = openFileDialog.File; ExtendedImage extendedImage = new ExtendedImage(); extendedImage.SetSource(fileInfo.OpenRead()); Image.Source = extendedImage; } }
public static WriteableBitmap GetBitmapSource(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) { try { // Tries to load the image using Windows Phone's internals. BitmapImage image = null; image = new BitmapImage(); image.SetSource(ms); return(new WriteableBitmap(image)); } catch (Exception) { try { // Resets the memory stream's position. ms.Position = 0; // It didn't work. Now try with ImageTools. ExtendedImage eim = new ExtendedImage(); eim.SetSource(ms); // Gets the image source for the image. WriteableBitmap bs = GetBitmapSource(eim); if (bs == null) { // Something went wrong. DebugUtils.DumpData(data, "ImageTools failed to generate an image source."); } return(bs); } catch (Exception e) { // Dump data! DebugUtils.DumpData(data, e); return(null); } } } }
private void UpdateImage() { if (SourceStream == null) { return; } SourceStream.Seek(0, SeekOrigin.Begin); try { if (IsGif) { GifImage = new ExtendedImage(); GifImage.SetSource(SourceStream); } else { Image = new BitmapImage(); Image.SetSource(SourceStream); SourceStream.Dispose(); SourceStream = null; } OnImageOpened(); } catch { Image = null; GifImage = null; if (!IsGif && IsEmotion) { IsGif = !IsGif; UpdateImage(); } else { OnImageOpenFailed(); } } }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); if (NavigationContext.QueryString.TryGetValue("imageUri", out imageFileName)) { FilenameText.Text = imageFileName; using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(imageFileName, System.IO.FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication())) { // Allocate an array large enough for the entire file byte[] data = new byte[stream.Length]; // Read the entire file and then close it stream.Read(data, 0, data.Length); stream.Close(); ExtendedImage image = new ExtendedImage(); image.LoadingCompleted += (o, ea) => Dispatcher.BeginInvoke(() => { AnimatedImage.Source = image; }); image.SetSource(new MemoryStream(data)); } } }
// 이미지 로딩 부분 UI 스레드에서 이루어짐 private async Task LoadImageAsync(ListBox panel, Grid grid, Picture pic) { // Status를 위한 텍스트 블럭 삽입 var status = new TextBlock(); try { status.Text = "[이미지를 불러오는 중..]"; grid.Children.Add(status); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HttpUtility.HtmlDecode(pic.Uri)); request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"; request.Method = "GET"; // 빈 스트링인 경우 요청이 예외가 난다 if (pic.Referer != string.Empty) { request.Headers["Referer"] = pic.Referer; } request.CookieContainer = WebClientEx.CookieContainer; HttpWebResponse response = (HttpWebResponse)await Task <WebResponse> .Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null); MemoryStream stream = new MemoryStream((int)response.ContentLength); await response.GetResponseStream().CopyToAsync(stream); stream.Seek(0, SeekOrigin.Begin); if (response.ContentType.Equals("image/gif", StringComparison.CurrentCultureIgnoreCase)) { // grid의 위치를 알아내고 int i = panel.Items.IndexOf(grid) + 1; ExtendedImage source = new ExtendedImage(); source.SetSource(stream); var image = new AnimatedImage(); image.Source = source; image.Tap += image_Tap; image.Tag = pic; image.LoadingFailed += (o, e) => { var tb = new TextBlock(); tb.Text = "로딩 실패"; tb.Foreground = new SolidColorBrush(Colors.Red); grid.Children.Add(tb); }; panel.Items.Insert(i, image); } // 이상하게도 PictureDecoder.DecodeJpeg이 png까지 디코딩을 할 수가 있어서.. 그냥 쓰고 있다 else if (response.ContentType.Equals("image/jpg", StringComparison.CurrentCultureIgnoreCase) || response.ContentType.Equals("image/jpeg", StringComparison.CurrentCultureIgnoreCase) || response.ContentType.Equals("image/png", StringComparison.CurrentCultureIgnoreCase)) { // 큰 이미지를 잘게 나눈다 var wbmps = await Task.Factory.StartNew(() => LoadImage(stream)); // grid의 위치를 알아내고 int i = panel.Items.IndexOf(grid) + 1; foreach (var wbmp in wbmps) { var image = new Image(); image.Source = wbmp; image.Tag = pic; image.Tap += image_Tap; panel.Items.Insert(i, image); i++; } // panel.Items.RemoveAt(i); } else { var source = new BitmapImage(); source.SetSource(stream); int i = panel.Items.IndexOf(grid) + 1; var image = new Image(); image.Source = source; image.Tag = pic; image.Tap += image_Tap; panel.Items.Insert(i, image); } grid.Children.Clear(); } catch { status.Text = "[이미지 불러오기 실패]"; } }
public void Execute() { try { var m = new ServiceManager <GetImageCompletedEventArgs>(delegate(BodyArchitectAccessServiceClient client1, EventHandler <GetImageCompletedEventArgs> operationCompleted) { using (OperationContextScope ocs = new OperationContextScope(client1.InnerChannel)) { OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("SessionId", "http://MYBASERVICE.TK/", ApplicationState.Current.SessionData.Token.SessionId)); OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("PictureId", "http://MYBASERVICE.TK/", picture.PictureIdk__BackingField)); OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("Hash", "http://MYBASERVICE.TK/", picture.Hashk__BackingField)); ApplicationState.AddCustomHeaders(); client1.GetImageCompleted -= operationCompleted; client1.GetImageCompleted += operationCompleted; client1.GetImageAsync(); } }); m.OperationCompleted += (s, a) => { if (a.Error != null) { PictureCacheItem item = new PictureCacheItem(null, picture.PictureIdk__BackingField, picture.Hashk__BackingField); PicturesCache.Instance.AddToCache(item); PicturesCache.Instance.Notify(new PictureInfoDTO() { PictureIdk__BackingField = picture.PictureIdk__BackingField, Hashk__BackingField = picture.Hashk__BackingField }); } else if (a.Result != null) { MemoryStream stream = new MemoryStream(a.Result.Result); ExtendedImage desert = new ExtendedImage(); desert.SetSource(stream); desert.LoadingFailed += delegate(object sender, UnhandledExceptionEventArgs e) { PictureCacheItem item = new PictureCacheItem(null, picture.PictureIdk__BackingField, picture.Hashk__BackingField); PicturesCache.Instance.AddToCache(item); PicturesCache.Instance.Notify(new PictureInfoDTO() { PictureIdk__BackingField = picture.PictureIdk__BackingField, Hashk__BackingField = picture.Hashk__BackingField }); }; desert.LoadingCompleted += delegate { ApplicationState.SynchronizationContext.Post(delegate { var image = desert.ToBitmap(); PictureCacheItem item = new PictureCacheItem(image, picture.PictureIdk__BackingField, picture.Hashk__BackingField); PicturesCache.Instance.AddToCache(item); PicturesCache.Instance.Notify(picture); //if (OperationCompleted != null) //{ // OperationCompleted(this, EventArgs.Empty); //} }, null); }; } }; m.Run(); } catch (Exception) { PictureCacheItem item = new PictureCacheItem(null, picture.PictureIdk__BackingField, picture.Hashk__BackingField); PicturesCache.Instance.AddToCache(item); PicturesCache.Instance.Notify(new PictureInfoDTO() { PictureIdk__BackingField = picture.PictureIdk__BackingField, Hashk__BackingField = picture.Hashk__BackingField }); } }