/// <summary> /// Creates a WPF bitmap source from an GDI image. /// </summary> public static BitmapSource CreateBitmapSource(Image image) { MemoryStream stream = new MemoryStream(); //int width = image.Width; //int height = image.Height; //double dpiX = image.HorizontalResolution; //double dpiY = image.VerticalResolution; //System.Windows.Media.PixelFormat pixelformat = PixelFormats.Default; BitmapSource bitmapSource = null; try { string guid = image.RawFormat.Guid.ToString("B").ToUpper(); switch (guid) { case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}": // memoryBMP case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}": // bmp image.Save(stream, ImageFormat.Bmp); stream.Position = 0; BmpBitmapDecoder bmpDecoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); bitmapSource = bmpDecoder.Frames[0]; break; case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}": // png image.Save(stream, ImageFormat.Png); stream.Position = 0; PngBitmapDecoder pngDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); bitmapSource = pngDecoder.Frames[0]; break; case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg image.Save(stream, ImageFormat.Jpeg); JpegBitmapDecoder jpegDecoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = jpegDecoder.Frames[0]; break; case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif image.Save(stream, ImageFormat.Gif); GifBitmapDecoder gifDecoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = gifDecoder.Frames[0]; break; case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff image.Save(stream, ImageFormat.Tiff); TiffBitmapDecoder tiffDecoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = tiffDecoder.Frames[0]; break; case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon image.Save(stream, ImageFormat.Icon); IconBitmapDecoder iconDecoder = new IconBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default); stream.Position = 0; bitmapSource = iconDecoder.Frames[0]; break; case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX default: throw new InvalidOperationException("Unsupported image format."); } } catch (Exception ex) { Debug.WriteLine("ImageHelper.CreateBitmapSource failed:" + ex.Message); } finally { //if (stream != null) // stream.Close(); } return bitmapSource; }
private void GifImage_Initialized(object sender, EventArgs e) { gifDecoder = new GifBitmapDecoder(Uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); animation = new Int32Animation(0, gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, gifDecoder.Frames.Count / 10, (int)((gifDecoder.Frames.Count / 10.0 - gifDecoder.Frames.Count / 10) * 1000)))); animation.RepeatBehavior = RepeatBehavior.Forever; Source = gifDecoder.Frames[0]; }
private void InitFromUri(Uri uri) { if (uri == null) { _gifDecoder = null; _animation = null; _animationIsWorking = false; return; } var decoder = BitmapDecoder.Create(uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); _gifDecoder = decoder as GifBitmapDecoder; if (_gifDecoder != null) { _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count/10, (int) ((_gifDecoder.Frames.Count/10.0 - _gifDecoder.Frames.Count/10)*1000)))) { RepeatBehavior = RepeatBehavior.Forever }; } else { _animation = null; _animationIsWorking = false; } Source = decoder.Frames[0]; }
private void btnOpenGIF_Click(object sender, EventArgs e) { bitmapList.Clear(); EntityList.Clear(); OpenFileDialog dialog = new OpenFileDialog(); if ( dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK ) { FileStream file = new FileStream(dialog.FileName, FileMode.Open); GifBitmapDecoder decoder = new GifBitmapDecoder(file, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); for ( int i = 0; i < decoder.Frames.Count; ++i ) { BitmapSource bitmapSource = decoder.Frames[i]; Bitmap bitmap = BitmapFromSource(bitmapSource); bitmapList.Add(bitmap); pictureBox1.Image = bitmap; imageList1.Images.Add(bitmap); ListViewItem item = listView1.Items.Add( i.ToString(), i ); item.ImageIndex = i; } } }
public AnimationGif(string strImagePath) { Stream stmImage; this.decAnimationGif = ImageProcessing.CreateGifBitmapDecoderFromResource(strImagePath, out stmImage); stmImage.Seek(0, SeekOrigin.Begin); var tmpImage = new System.Drawing.Bitmap(stmImage); var piFrameDelay = tmpImage.GetPropertyItem(0x5100); this.arrDelays = new int[this.decAnimationGif.Frames.Count]; for (int i = 0; i < this.arrDelays.Length; i++) { this.arrDelays[i] = BitConverter.ToInt32(piFrameDelay.Value, i * 4) * 10; } var piLoopCount = tmpImage.GetPropertyItem(0x5101); this.nLoop = BitConverter.ToInt16(piLoopCount.Value, 0); this.nLoopRemain = this.nLoop; BitmapFrame frame = this.decAnimationGif.Frames.First(); this.imgFrame = new Image(); this.imgFrame.Source = frame; this.imgFrame.Stretch = Stretch.None; this.imgFrame.Width = frame.PixelWidth; this.imgFrame.Height = frame.PixelHeight; this.timerInterval = new DispatcherTimer(); this.timerInterval.Interval = new TimeSpan(0, 0, 0, 0, this.arrDelays[0]); this.timerInterval.Tick += new EventHandler(AnimationHandler); this.timerInterval.Start(); }
public GifImage(Uri uri) { gf = new GifBitmapDecoder(uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); anim = new Int32Animation(0, gf.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, gf.Frames.Count / 10, (int)((gf.Frames.Count / 10.0 - gf.Frames.Count / 10) * 1000)))); anim.RepeatBehavior = RepeatBehavior.Forever; Source = gf.Frames[0]; }
private void LocaleSelectForm_Load(object sender, EventArgs e) { BorderSize = Size - ClientRectangle.Size; Size = new Size(MaxWidth + 2 * BorderSize.Width, MaxHeight + BorderSize.Height + BorderSize.Width + 40); DirectoryInfo dInfo = new DirectoryInfo(Path.Combine(Application.StartupPath, "Locales")); FileInfo[] localeFiles = dInfo.GetFiles("*.xml"); if (localeFiles.Length == 0) { MessageBox.Show(@"Error - No o!RA locales exist! Re-install the application and try again.\o!RA will now exit."); Application.Exit(); } //Get all the locales and put usercontrols on form foreach (FileInfo file in localeFiles) { string localeName = file.Name.Substring(0, file.Name.LastIndexOf(".", StringComparison.InvariantCulture)); Stream str = ResourceHelper.GetResourceStream("flag_" + localeName + ".gif"); if (str != null) { //Add usercontrol GifBitmapDecoder gDecoder = new GifBitmapDecoder(str, BitmapCreateOptions.None, BitmapCacheOption.OnDemand); LanguageBox lb = new LanguageBox { Locale = localeName, MouseOverImage = BitmapFromSource(gDecoder.Frames[1]), NormalImage = BitmapFromSource(gDecoder.Frames[0]) }; Controls.Add(lb); LocaleBoxes.Add(lb); } } currentStart = 0; PopulateForm(); }
/// <summary> /// Initializes a new instance of the <see cref="AnimatedLoader" /> class. /// </summary> public AnimatedLoader() { Visibility = Visibility.Hidden; IsVisibleChanged += LoaderVisibilityChanged; var imageSource = Application.Current.Resources["LoaderImage"] as ImageSource; var loaderUri = imageSource == null ? new Uri("pack://application:,,,/Nova;component/Resources/loader.gif", UriKind.Absolute) : new Uri(imageSource.ToString(), UriKind.Absolute); _gifBitmapDecoder = new GifBitmapDecoder(loaderUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); var seconds = _gifBitmapDecoder.Frames.Count/10; var milliseconds = (int) (((_gifBitmapDecoder.Frames.Count/10.0) - (_gifBitmapDecoder.Frames.Count/10.0))*1000d); var timespan = new TimeSpan(0, 0, 0, seconds, milliseconds); var duration = new Duration(timespan); _animation = new Int32Animation(0, _gifBitmapDecoder.Frames.Count - 1, duration) { RepeatBehavior = RepeatBehavior.Forever }; Source = _gifBitmapDecoder.Frames[0]; Height = Source.Height; Width = Source.Width; }
protected override void OnInitialized(EventArgs e) { gf = new GifBitmapDecoder(new Uri(Uri, UriKind.RelativeOrAbsolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); anim = new Int32Animation(0, gf.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, gf.Frames.Count / (int)fps, (int)((gf.Frames.Count / (double)fps - gf.Frames.Count / (int)fps) * 1000)))); anim.RepeatBehavior = RepeatBehavior.Forever; Source = gf.Frames[0]; }
public GifImage() { Uri uri = new Uri("pack://application:,,,/AssortmentManagement;component/Images/load.gif"); gf = new GifBitmapDecoder(uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); anim = new Int32Animation(0, gf.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, gf.Frames.Count / 10, (int)((gf.Frames.Count / 10.0 - gf.Frames.Count / 10) * 1000)))); anim.RepeatBehavior = RepeatBehavior.Forever; Source = gf.Frames[0]; }
private void Initialize() { _gifDecoder = FASTBuildMonitorControl.GetGifBitmapDecoder(GifSource); _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count / 10, (int)((_gifDecoder.Frames.Count / 10.0 - _gifDecoder.Frames.Count / 10) * 1000)))); _animation.RepeatBehavior = RepeatBehavior.Forever; this.Source = _gifDecoder.Frames[0]; _isInitialized = true; }
private void Initialize() { _gifDecoder = new GifBitmapDecoder(new Uri("pack://application:,,," + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count / 10, (int)((_gifDecoder.Frames.Count / 10.0 - _gifDecoder.Frames.Count / 10) * 1000)))); _animation.RepeatBehavior = RepeatBehavior.Forever; this.Source = _gifDecoder.Frames[0]; _isInitialized = true; }
private void onInitialized(object sender, EventArgs e) { gf = new GifBitmapDecoder(new Uri(GifUri), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); var millisecondPerFrame = 1000.0 / Convert.ToDouble(FramesPerSecond); anim = new Int32Animation(0, gf.Frames.Count - 1, TimeSpan.FromMilliseconds(millisecondPerFrame * gf.Frames.Count)) { RepeatBehavior = RepeatBehavior.Forever }; Source = gf.Frames[0]; }
protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); var stream = Application.GetResourceStream(new Uri(Source.ToString())); m_gf = new GifBitmapDecoder(stream.Stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); m_anim = new Int32Animation(0, m_gf.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, m_gf.Frames.Count / 10, (int)((m_gf.Frames.Count / 10.0 - m_gf.Frames.Count / 10) * 1000)))); m_anim.RepeatBehavior = RepeatBehavior.Forever; Source = m_gf.Frames[0]; }
protected override void OnInitialized(EventArgs e) { decoder = new GifBitmapDecoder(Uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); animation = new Int32Animation(0, decoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, decoder.Frames.Count / 10, (int) ((decoder.Frames.Count / 10.0 - decoder.Frames.Count / 10) * 1000)))) { RepeatBehavior = RepeatBehavior.Forever }; Source = decoder.Frames[0]; }
private void Initialize() { if (!DesignerProperties.GetIsInDesignMode(this)) { _gifDecoder = new GifBitmapDecoder(new Uri("pack://application:,,,/OAuth;component/" + GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count / 10, (int)((_gifDecoder.Frames.Count / 10.0 - _gifDecoder.Frames.Count / 10) * 1000)))) { RepeatBehavior = RepeatBehavior.Forever }; Source = _gifDecoder.Frames[0]; _isInitialized = true; } }
public void setGifSource(string url) { // initialize the gifDecoder _gifDecoder = new GifBitmapDecoder(new Uri(url), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); // initialize the animation _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count / 10, (int)((_gifDecoder.Frames.Count / 10.0 - _gifDecoder.Frames.Count / 10) * 1000)))); // repeat forever _animation.RepeatBehavior = RepeatBehavior.Forever; // set the image source this.Source = _gifDecoder.Frames[0]; this.StartAnimation(); }
private void RefreshGif() { if (string.IsNullOrEmpty(_gifSource?.ToString())) return; _gf = new GifBitmapDecoder(_gifSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); _anim = new Int32Animation(0, _gf.Frames.Count - 1, new Duration(TimeSpan.FromSeconds(_gf.Frames.Count/FramesPerSecond))) { RepeatBehavior = RepeatBehavior.Forever }; Source = _gf.Frames[0]; }
private void GifSourceChanged(string newSource) { if (_animation != null) BeginAnimation(FrameIndexProperty, null); _decoder = new GifBitmapDecoder(new Uri(newSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); Source = _decoder.Frames[0]; int count = _decoder.Frames.Count; _animation = new Int32Animation(0, count - 1, new Duration(new TimeSpan(0, 0, 0, count / 10, (int)((count / 10.0 - count / 10) * 1000)))); _animation.RepeatBehavior = RepeatBehavior.Forever; BeginAnimation(FrameIndexProperty, _animation); }
public void CreateGifAnimation(MemoryStream memoryStream) { Reset(); byte[] gifData = memoryStream.GetBuffer(); // Use GetBuffer so that there is no memory copy GifBitmapDecoder decoder = new GifBitmapDecoder(memoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); numberOfFrames = decoder.Frames.Count; try { ParseGif(gifData); } catch { throw new FileFormatException("Unable to parse Gif file format."); } for (int i = 0; i < decoder.Frames.Count; i++) { frameList[i].Source = decoder.Frames[i]; frameList[i].Visibility = Visibility.Hidden; canvas.Children.Add(frameList[i]); Canvas.SetLeft(frameList[i], frameList[i].left); Canvas.SetTop(frameList[i], frameList[i].top); Canvas.SetZIndex(frameList[i], i); } canvas.Height = logicalHeight; canvas.Width = logicalWidth; frameList[0].Visibility = Visibility.Visible; for (int i = 0; i < frameList.Count; i++) { Console.WriteLine(frameList[i].disposalMethod.ToString() + " " + frameList[i].width.ToString() + " " + frameList[i].delayTime.ToString()); } if (frameList.Count > 1) { if (numberOfLoops == -1) { numberOfLoops = 1; } frameTimer = new System.Windows.Threading.DispatcherTimer(); frameTimer.Tick += NextFrame; frameTimer.Interval = new TimeSpan(0, 0, 0, 0, frameList[0].delayTime * 10); frameTimer.Start(); } }
public void CreateGifAnimation(MemoryStream memoryStream) { this.Reset(); byte[] gifData = memoryStream.GetBuffer(); GifBitmapDecoder decoder = new GifBitmapDecoder(memoryStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); this._numberOfFrames = decoder.Frames.Count; try { this.ParseGif(gifData); } catch { throw new FileFormatException("Unable to parse Gif file format."); } for (int i = 0; i < decoder.Frames.Count; i++) { this._frameList[i].Source = decoder.Frames[i]; this._frameList[i].Visibility = Visibility.Hidden; } this._canvas.Height = this._logicalHeight; this._canvas.Width = this._logicalWidth; this._frameList[0].Visibility = Visibility.Visible; for (int j = 0; j < this._frameList.Count; j++) { Console.WriteLine(this._frameList[j].disposalMethod.ToString() + " " + this._frameList[j].width.ToString() + " " + this._frameList[j].delayTime.ToString()); } if (this._frameList.Count > 1) { if (this._numberOfLoops == -1) { this._numberOfLoops = 1; } this.SetTimer(this._frameList[0].delayTime * 10); } base.InvalidateVisual(); }
internal static BitmapSource ToImageSource(string ext, Stream s) { ext = ext.ToLower(); if (ext.EndsWith(".png")) { var bitmapDecoder = new PngBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); return bitmapDecoder.Frames[0]; } if (ext.EndsWith(".gif")) { var bitmapDecoder = new GifBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); return bitmapDecoder.Frames[0]; } if (ext.EndsWith(".jpg")) { var bitmapDecoder = new JpegBitmapDecoder(s, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); return bitmapDecoder.Frames[0]; } // http://stackoverflow.com/questions/2835502/rotating-cursor-according-to-rotated-textbox // http://stackoverflow.com/questions/46805/custom-cursor-in-wpf // http://stackoverflow.com/questions/2284353/is-there-a-good-way-to-convert-between-bitmapsource-and-bitmap // http://www.gdgsoft.com/anituner/help/aniformat.htm // http://msdn.microsoft.com/en-us/library/ms608877.aspx throw new NotSupportedException(ext); }
private bool IsAnimatedGifImage(BitmapImage aBitmapImage) { Debug.Assert(aBitmapImage != null); bool lResult = false; if(aBitmapImage.UriSource != null) { BitmapDecoder lBitmapDecoder = BitmapDecoder.Create( aBitmapImage.UriSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); lResult = lBitmapDecoder is GifBitmapDecoder; } else if(aBitmapImage.StreamSource != null) { try { long lStreamPosition = aBitmapImage.StreamSource.Position; aBitmapImage.StreamSource.Position = 0; GifBitmapDecoder lBitmapDecoder = new GifBitmapDecoder( aBitmapImage.StreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); lResult = lBitmapDecoder.Frames.Count > 1; aBitmapImage.StreamSource.Position = lStreamPosition; } catch { lResult = false; } } return lResult; }
public void Blockchange2(Player p, ushort x, ushort y, ushort z, byte Type) { ppos.x = p.pos[0]; ppos.y = p.pos[1]; ppos.z = p.pos[2]; pllvl = p.level.name; blox[1].x = x; blox[1].y = y; blox[1].z = z;// jetz direction rausfinden und dann unten verwenden. int direction; //1 = 0,0,0 nach 1,0,0 2= 0,0,0 nach 0,1,0 3= 1,0,0 nach 0 und 4 = 010 nach 0 if (blox[1].x > blox[0].x) { direction = 1; p.SendMessage("dir1"); } else if (blox[1].x < blox[0].x) { direction = 3; p.SendMessage("dir3"); } else if (blox[1].z > blox[0].z) { direction = 2; p.SendMessage("dir2"); } else if (blox[1].z < blox[0].z) { direction = 4; p.SendMessage("dir4"); } else { direction = 1; p.SendMessage("else"); } String cinName = ""; cinName = msg; using (Stream imageStreamSource = new FileStream("extra/images/" + msg + ".gif", FileMode.Open, FileAccess.Read, FileShare.Read)) { GifBitmapDecoder decoder = new GifBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); for (int i = 0; i < decoder.Frames.Count; i++) { //saving all frames as pngs. BitmapSource bitmapSource = decoder.Frames[i]; using (FileStream fs = new FileStream("extra/images/" + i.ToString() + ".bmp", FileMode.Create)) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(fs); } } using (System.Drawing.Bitmap tbmp = new System.Drawing.Bitmap("extra/images/0.bmp")) { picHeight = tbmp.Height; picWidth = tbmp.Width; //create the new map... Command.all.Find("newlvl").Use(p, "gtctempmap " + picWidth.ToString() + " " + picHeight.ToString() + " " + picWidth.ToString() + " space"); Command.all.Find("load").Use(p, "gtctempmap"); //moving the player to this map Command.all.Find("move").Use(p, p.name + " gtctempmap"); System.Threading.Thread.Sleep(2000); for (int i = 0; i < decoder.Frames.Count; i++) { p.SendMessage("Start processing Frame " + i); workFrame(i, p, cinName, direction); p.SendMessage("Done"); } p.SendMessage("YAY! everything should be done"); Command.all.Find("move").Use(p, p.name + " " + pllvl); unchecked { p.SendPos((byte)-1, ppos.x, ppos.y, ppos.z, 0, 0); } Command.all.Find("deletelvl").Use(p, "gtctempmap");//deleting templvl for (int i = 0; i < decoder.Frames.Count; i++) { File.Delete("extra/images/" + i.ToString() + ".bmp"); } } } }
public static void SetImageSource(Image imageElement, GifBitmapDecoder gif, int frameIndex) { GUIDispatcher.BeginInvoke((Action)(() => { imageElement.Source = gif.Frames[frameIndex]; })); }
internal static BitmapDecoder CreateFromUriOrStream( Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy, bool insertInDecoderCache ) { Guid clsId = Guid.Empty; bool isOriginalWritable = false; SafeMILHandle decoderHandle = null; BitmapDecoder cachedDecoder = null; Uri finalUri = null; Stream uriStream = null; UnmanagedMemoryStream unmanagedMemoryStream = null; SafeFileHandle safeFilehandle = null; // check to ensure that images are allowed in partial trust DemandIfImageBlocked(); if (uri != null) { finalUri = (baseUri != null) ? System.Windows.Navigation.BaseUriHelper.GetResolvedUri(baseUri, uri) : uri; if (insertInDecoderCache) { if ((createOptions & BitmapCreateOptions.IgnoreImageCache) != 0) { ImagingCache.RemoveFromDecoderCache(finalUri); } cachedDecoder = CheckCache( finalUri, out clsId ); } } // try to retrieve the cached decoder if (cachedDecoder != null) { decoderHandle = cachedDecoder.InternalDecoder; } else if ((finalUri != null) && (finalUri.IsAbsoluteUri) && (stream == null) && ((finalUri.Scheme == Uri.UriSchemeHttp) || (finalUri.Scheme == Uri.UriSchemeHttps))) { return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy); } else if ((stream != null) && (!stream.CanSeek)) { return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy); } else { // Create an unmanaged decoder decoderHandle = BitmapDecoder.SetupDecoderFromUriOrStream( finalUri, stream, cacheOption, out clsId, out isOriginalWritable, out uriStream, out unmanagedMemoryStream, out safeFilehandle ); } BitmapDecoder decoder = null; // Find out the decoder type and wrap it appropriately and return that if (MILGuidData.GUID_ContainerFormatBmp == clsId) { decoder = new BmpBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatGif == clsId) { decoder = new GifBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatIco == clsId) { decoder = new IconBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatJpeg == clsId) { decoder = new JpegBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatPng == clsId) { decoder = new PngBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatTiff == clsId) { decoder = new TiffBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else if (MILGuidData.GUID_ContainerFormatWmp == clsId) { decoder = new WmpBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } else { decoder = new UnknownBitmapDecoder( decoderHandle, cachedDecoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, isOriginalWritable, uriStream, unmanagedMemoryStream, safeFilehandle ); } return decoder; }
public void Load() { try { // If we have a loading function, use that to get the url we want to load if (loading != null) this.url = loading(); // We explicitly use the WebClient here because we need access to the system-wide browser cache and cookies collection var client = new WebClient { CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable) }; var stream = new MemoryStream(); using (var istream = client.OpenRead(url)) { // Read stream into our own byte buffer on the background thread istream.CopyTo(stream); stream.Seek(0, SeekOrigin.Begin); } var headers = client.ResponseHeaders; Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate { try { // Create imagesource on the foreground thread string extension = Path.GetExtension(url).ToLower(); BitmapDecoder decoder = null; if (extension == ".gif") decoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); else if (extension == ".png") decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); else if (extension == ".jpg" || extension == ".jpeg") decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); else if (extension == ".bmp") decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); else { // We are not sure what extension we are looking at, lets see if there is a content-type available if (headers["Content-Type"] != null) { var type = headers["Content-Type"]; if (type.IndexOf("gif", StringComparison.InvariantCultureIgnoreCase) > -1) decoder = new GifBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); else if (type.IndexOf("png", StringComparison.InvariantCultureIgnoreCase) > -1) decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); else if (type.IndexOf("jpg", StringComparison.InvariantCultureIgnoreCase) > -1 || type.IndexOf("jpeg", StringComparison.InvariantCultureIgnoreCase) > -1) decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); else if (type.IndexOf("bmp", StringComparison.InvariantCultureIgnoreCase) > -1) decoder = new BmpBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } } if (decoder == null) { Logger.Error("Unable to determine type of image to decode. url = {0}", LogSource.BackgroundTask, url); return; } _asyncSource = decoder.Frames[0]; _asyncSource.Freeze(); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("AsyncSource")); if (loaded != null) loaded(); } catch (Exception ex) { Logger.Error("An error has occured while trying to download an AsyncHttpImage. Url = {0} Exception = {1}", LogSource.BackgroundTask, url, ex); } finally { stream.Dispose(); } }); } catch (Exception ex) { Logger.Error("An error has occured while trying to download an AsyncHttpImage. Url = {0} Exception = {1}", LogSource.BackgroundTask, url, ex); } }
private void Initialize() { _gifDecoder = new GifBitmapDecoder(new Uri("pack://application:,,," + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration( TimeSpan.FromMilliseconds( ((ushort)(_gifDecoder.Frames[0].Metadata as BitmapMetadata).GetQuery("/grctlext/Delay")) * 10 * _gifDecoder.Frames.Count))) { RepeatBehavior = RepeatBehavior.Forever }; this.Source = _gifDecoder.Frames[0]; _isInitialized = true; }
private GifBitmapDecoder openFileDialog() { sourceStream = null; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { Console.WriteLine(openFileDialog1.FileName); if ((sourceStream = openFileDialog1.OpenFile()) != null) { GifBitmapDecoder decoder = new GifBitmapDecoder(sourceStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); return decoder; } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } return null; }
private void PrepareAnimation(System.Windows.Media.Imaging.BitmapImage aBitmapImage) { System.Diagnostics.Debug.Assert(aBitmapImage != null); if (aBitmapImage.UriSource != null) { Decoder = new GifBitmapDecoder( aBitmapImage.UriSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); } else { aBitmapImage.StreamSource.Position = 0; Decoder = new GifBitmapDecoder( aBitmapImage.StreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); } Animation = new Int32Animation( 0, Decoder.Frames.Count - 1, new Duration( new TimeSpan( 0, 0, 0, Decoder.Frames.Count / 10, (int)((Decoder.Frames.Count / 10.0 - Decoder.Frames.Count / 10) * 1000)))) { RepeatBehavior = RepeatBehavior.Forever }; base.Source = Decoder.Frames[0]; BeginAnimation(FrameIndexProperty, Animation); IsAnimationWorking = true; }