public static Tuple<BitmapSource, byte[]> Convert(this IEnumerable<PointFrame> cloud, int width, int height) { var bytes = new byte[cloud.Count() * (PixelFormats.Bgr32.BitsPerPixel / 8)]; byte[] result; var index = 0; foreach (var point in cloud) { bytes[index++] = (byte)point.B; // Blue bytes[index++] = (byte)point.G; // Green bytes[index++] = (byte)point.R; // Red } var source = BitmapSource.Create(width, height, 96, 96, PixelFormats.Rgb24, BitmapPalettes.Gray16, bytes, width * PixelFormats.Rgb24.BitsPerPixel / 8); var encoder = new GifBitmapEncoder(); using (var stream = new MemoryStream()) { encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(stream); result = stream.ToArray().Select(s => (byte)(sbyte)s).ToArray(); stream.Close(); } return Tuple.Create(source, result); }
public void A() { int width = 128; int height = width; int stride = width / 8; byte[] pixels = new byte[height * stride]; BitmapPalette myPalette = BitmapPalettes.WebPalette; BitmapSource image = BitmapSource.Create( width, height, 96, 96, PixelFormats.Indexed1, myPalette, pixels, stride); BitmapSource A = BitmapConverter.GetBitmapSource(Properties.Resources._1); BitmapSource B = BitmapConverter.GetBitmapSource(Properties.Resources._2); FileStream stream = new FileStream("new.gif", FileMode.Create); GifBitmapEncoder encoder = new GifBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(A)); encoder.Frames.Add(BitmapFrame.Create(B)); encoder.Save(stream); }
static void Main() { #region License RuntimeManager.Bind(ProductCode.EngineOrDesktop); var ao = new AoInitialize(); var code = new[] { 60, 50, 40, 10 }.Cast<esriLicenseProductCode>().First(c => ao.IsProductCodeAvailable(c) == esriLicenseStatus.esriLicenseAvailable); ao.Initialize(code); #endregion var grid = new Grid("ascii.txt", true); var fileName = "GospersGliderGun.gif"; var iteration = 100; var encoder = new GifBitmapEncoder(); for (var i = 0; i < iteration; i++) { Console.WriteLine($"Processing {i + 1} of {iteration}..."); var tempFileName = $@"{Path.GetTempPath()}\{Guid.NewGuid()}.png"; Resample(200 * grid, 0.1).Save(tempFileName); encoder.Frames.Add(BitmapFrame.Create(new Uri(tempFileName))); grid = Tick(grid); } using (var s = new System.IO.FileStream(fileName, FileMode.Create)) encoder.Save(s); Process.Start(fileName); }
/// custom private static void createGif(IEnumerable <Bitmap> bitmaps, string path) { var gifEnc = new Media.Imaging.GifBitmapEncoder(); foreach (var bmp in bitmaps) { var src = Interop.Imaging.CreateBitmapSourceFromHBitmap( bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, Media.Imaging.BitmapSizeOptions.FromEmptyOptions() ); var emptyBmp = new Bitmap(bmp.Width, bmp.Height); /* * Graphics g = Graphics.FromImage(emptyBmp); * g.FillRectangle(new SolidBrush(Color.White), 0, 0, bmp.Width, bmp.Height); * g.Dispose(); * * var emptyFrame = Interop.Imaging.CreateBitmapSourceFromHBitmap( * emptyBmp.GetHbitmap(), * IntPtr.Zero, * Int32Rect.Empty, * Media.Imaging.BitmapSizeOptions.FromEmptyOptions() * ); * gifEnc.Frames.Add(Media.Imaging.BitmapFrame.Create(src)); */ } using (var fs = new FileStream(path, FileMode.Create)) { gifEnc.Save(fs); } }
public void Animate(FinalRender renderer) { FileStream stream = new FileStream(@"TMP.GIF", FileMode.Create); var encoder = new System.Windows.Media.Imaging.GifBitmapEncoder(); foreach (var f in frames) { encoder.Frames.Add(BitmapFrame.Create(toBitmapConvert(f))); } encoder.Save(stream); stream.Close(); var test = new Jillzhang.GifUtility.GifDecoder(); test.Decode(@"TMP.GIF"); foreach (var frame in test.Frames) { frame.Delay = (short)((double)100 / Animatronic.FRAMES_PER_SECOND); } var test2 = new Jillzhang.GifUtility.GifEncoder(@"TMP.GIF"); test2.Encode(test); //var w = new Jillzhang.GifUtility.GifHelper(); //w.WaterMark(@"TMP2.GIF", "Distributed RT - ITCS 422", Color.White, new Font(new FontFamily("Arial"), 8), 0, 0, @"TMP2.GIF"); renderer.Picture.LoadAsync(@"TMP.GIF"); }
public byte[] getGIFFromImageControl(BitmapImage imageC) { MemoryStream memStream = new MemoryStream(); GifBitmapEncoder encoder = new GifBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(imageC)); encoder.Save(memStream); return memStream.GetBuffer(); }
public static bool ConvertToGif(this List<BitmapSource> bmps, string filepath) { FileStream stream = new FileStream(filepath, FileMode.OpenOrCreate); GifBitmapEncoder encoder = new GifBitmapEncoder(); bmps.ForEach(i => { encoder.Frames.Add(BitmapFrame.Create(i)); }); encoder.Save(stream); return true; }
static void bi_DownloadCompleted(object sender, EventArgs e) { string fullPath = System.Reflection.Assembly.GetAssembly(typeof(Microsoft.Samples.SqlServer.WordAddIn.WorkflowRibbon)).Location; string gifPath = String.Format(@"{0}$word.odata.gif", Path.GetDirectoryName(fullPath)); using (FileStream stream = new FileStream(gifPath, FileMode.Create)) { var encoder = new GifBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender)); encoder.Save(stream); } Globals.ThisAddIn.Application.Selection.InlineShapes.AddPicture(gifPath, false); }
//BlueMarble.Data.MarbleDataBase dataBase; public void InitiateVideo(int rollNum, int frameRate) { FileStream stream = new FileStream("new.gif", FileMode.Create); Stream imageStream = new FileStream("images.jpg", FileMode.Open, FileAccess.Read, FileShare.Read); JpegBitmapDecoder decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource image = decoder.Frames[0]; GifBitmapEncoder newGif = new GifBitmapEncoder(); for (int x = 0; x < 10; x++) { newGif.Frames.Add(BitmapFrame.Create(image)); } bool duration = newGif.Frames[0].HasAnimatedProperties; imageStream = new FileStream("images2.jpg", FileMode.Open, FileAccess.Read, FileShare.Read); decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); image = decoder.Frames[0]; for (int x = 0; x < 10; x++) { newGif.Frames.Add(BitmapFrame.Create(image)); } imageStream = new FileStream("images3.jpg", FileMode.Open, FileAccess.Read, FileShare.Read); decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); image = decoder.Frames[0]; for (int x = 0; x < 10; x++) { newGif.Frames.Add(BitmapFrame.Create(image)); } var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"); using (var response = request.GetResponse()) using (var webstream = response.GetResponseStream()) { decoder = new JpegBitmapDecoder(webstream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); //imageStream = Bitmap.FromStream(webstream); } //decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); image = decoder.Frames[0]; for (int x = 0; x < 10; x++) { newGif.Frames.Add(BitmapFrame.Create(image)); } newGif.Save(stream); }
public static void saveImage(BitmapFrame bitmapFrame, string fileName) { FileStream outStream = new FileStream(fileName, FileMode.Create); string _fileName = fileName.ToLower(); if (_fileName.EndsWith(".png")) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(bitmapFrame); encoder.Save(outStream); outStream.Close(); } else if (_fileName.EndsWith(".jpg") || _fileName.EndsWith(".jpeg")) { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(bitmapFrame); encoder.Save(outStream); outStream.Close(); } else if (_fileName.EndsWith(".bmp")) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(bitmapFrame); encoder.Save(outStream); outStream.Close(); } else if (_fileName.EndsWith(".gif")) { GifBitmapEncoder encoder = new GifBitmapEncoder(); encoder.Frames.Add(bitmapFrame); encoder.Save(outStream); outStream.Close(); } else if (_fileName.EndsWith(".tiff")) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(bitmapFrame); encoder.Save(outStream); outStream.Close(); } }
public static void SaveGIF(this BitmapSource source, Stream stream, BitmapMetadata data, params BitmapSource[] additionals) { BitmapEncoder enc = new GifBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(source)); foreach(BitmapSource bs in additionals) enc.Frames.Add(BitmapFrame.Create(bs)); if (data != null) enc.Metadata = data; enc.Save(stream); }
/// <summary> /// GIFアニメーションにフレームを追加 /// </summary> /// <param name="frame">追加するBitmapFrame</param> /// <param name="delay">表示まで遅らせる時間[ms](最低10ms刻み)</param> public void Add(BitmapFrame frame, uint delay) { bool hasGlobalColorTable = false; int colorTableSize = 0; using (var ms = new MemoryStream()) { var encoder = new GifBitmapEncoder(); encoder.Frames.Add(frame); encoder.Save(ms); ms.Position = 0; if (counter == 0) { //ヘッダを書き込む //Header writer.Write(ReadBytes(ms, 6)); //Logical Screen Descriptor byte[] screenDescriptor = ReadBytes(ms, 7); //Global Color Tableがあるか確認 if ((screenDescriptor[4] & 0x80) != 0) { //Color Tableのサイズを取得 colorTableSize = screenDescriptor[4] & 0x07; hasGlobalColorTable = true; } else { hasGlobalColorTable = false; } //Global Color Tableを使わない //広域配色表フラグと広域配色表の寸法を消す screenDescriptor[4] = (byte)(screenDescriptor[4] & 0x78); writer.Write(screenDescriptor); //Application Extension writer.Write(GetApplicationExtension()); } else { //HeaderとLogical Screen Descriptorをスキップ ms.Position += 6 + 7; } byte[] colorTable = null; if (hasGlobalColorTable) { //Color Tableを取得 colorTable = ReadBytes(ms, (int)Math.Pow(2, colorTableSize + 1) * 3); } //Graphics Control Extension writer.Write(GetGraphicControlExtension(Convert.ToUInt16(delay / 10))); //基のGraphics Control Extensionをスキップ if (ms.GetBuffer()[ms.Position] == 0x21) { ms.Position += 8; } //Image Descriptor byte[] imageDescriptor = ReadBytes(ms, 10); if (!hasGlobalColorTable) { //Local Color Tableを持っているか確認 if ((imageDescriptor[9] & 0x80) == 0) throw new Exception("Not found color table."); //Color Tableのサイズを取得 colorTableSize = imageDescriptor[9] & 7; //Color Tableを取得 colorTable = ReadBytes(ms, (int)Math.Pow(2, colorTableSize + 1) * 3); } //狭域配色表フラグ (Local Color Table Flag) と狭域配色表の寸法を追加 imageDescriptor[9] = (byte)(imageDescriptor[9] | 0x80 | colorTableSize); writer.Write(imageDescriptor); //Local Color Tableを書き込む writer.Write(colorTable); //Image Dataを書き込む (終了部は書き込まない) writer.Write(ReadBytes(ms, (int)(ms.Length - ms.Position - 1))); //MemoryStreamをリセット //ms.SetLength(0); } counter++; }
private void BlackAndWhiteButton_Click(object sender, EventArgs e) { var selected = new Bitmap(LoadedFilePictureBox.Image); ManipulatedPictureBox.SizeMode = PictureBoxSizeMode.Zoom; if (LoadedPictureLabel.Text.Contains(".gif")) { Image gif = Image.FromFile(LoadedPictureLabel.Text); FrameDimension dimension = new FrameDimension(gif.FrameDimensionsList[0]); int frameCount = gif.GetFrameCount(dimension); GifBitmapEncoder encoder = new GifBitmapEncoder(); Bitmap[] frames = new Bitmap[frameCount]; for (int i = 0; i < frameCount; i++) { gif.SelectActiveFrame(dimension, i); frames[i] = new Bitmap(gif.Size.Width, gif.Size.Height); Graphics.FromImage(frames[i]).DrawImage(gif,new System.Drawing.Point(0,0)); frames[i] = Greyscale(frames[i]); var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( frames[i].GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); frames[i].Save("temp_" + i + ".png"); encoder.Frames.Add(BitmapFrame.Create(src)); } string tempFile = Directory.GetCurrentDirectory()+"\\temp.gif"; encoder.Save(new FileStream(tempFile, FileMode.Create)); ManipulatedPictureBox.Image = frames[0]; /* Stream source = new FileStream(LoadedPictureLabel.Text, FileMode.Open, FileAccess.Read, FileShare.Read); GifBitmapDecoder decoder = new GifBitmapDecoder(source, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); int numFrames = decoder.Frames.Count; GifBitmapEncoder encoder = new GifBitmapEncoder(); for (int i = 0; i < numFrames; i++) { BitmapSource singleFrame = decoder.Frames[i]; //int stride = singleFrame.PixelWidth*(singleFrame.Format.BitsPerPixel/8); //byte[] data2 = new byte[stride * singleFrame.PixelHeight]; //singleFrame.CopyPixels(data2, stride, 0); Bitmap temp = new Bitmap(singleFrame.PixelWidth, singleFrame.PixelHeight); BitmapData data = temp.LockBits(new Rectangle(System.Drawing.Point.Empty, temp.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); singleFrame.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); temp.UnlockBits(data); Bitmap newTemp = Greyscale(temp); BitmapData tempData = newTemp.LockBits(new Rectangle(System.Drawing.Point.Empty,newTemp.Size),ImageLockMode.WriteOnly,PixelFormat.Format32bppArgb); BitmapPalette palette = null; if (newTemp.Palette.Entries.Length > 0) { var palette_colors = newTemp.Palette.Entries.Select(entry => System.Windows.Media.Color.FromArgb(entry.A, entry.R, entry.G, entry.B)).ToList(); palette = new BitmapPalette(palette_colors); } //Now I need to create a new gif //new gif.addFrame(GreyScale(temp)); BitmapSource tempSource = BitmapSource.Create( newTemp.Width, newTemp.Height, (double)newTemp.HorizontalResolution, (double)newTemp.VerticalResolution, ConvertPixelFormat(newTemp.PixelFormat), palette, tempData.Scan0, tempData.Stride * newTemp.Height, tempData.Stride ); encoder.Frames.Add(BitmapFrame.Create(tempSource)); } FileStream stream = new FileStream("temp.gif", FileMode.Create); encoder.Save(stream); //ManipulatedPictureBox.Image.Save(stream.Name); selected = Greyscale(selected); ManipulatedPictureBox.Image = selected; * */ } else { selected = Greyscale(selected); ManipulatedPictureBox.Image = selected; } }
private void exportButton_Click(object sender, RoutedEventArgs e) { #if false var encoder = new GifBitmapEncoder(); for (var i = 0; i <= 100; i++) { var chapters = db.PlanetOwnerHistories.Where(h => h.Turn == i); foreach (var chapter in chapters) ApplyHistoryItem(chapter); mapCanvas.UpdateLayout(); var bitmap = new RenderTargetBitmap((int)viewBox.ActualWidth, (int)viewBox.ActualHeight, 96 * (int)viewBox.ActualWidth, 96 * (int)viewBox.ActualHeight, PixelFormats.Pbgra32); bitmap.Render(mapCanvas); encoder.Frames.Add(BitmapFrame.Create(bitmap)); Debug.WriteLine(i); } string path = @"C:\Users\Nubtron\Desktop\replay.gif"; var fileStream = new FileStream(path, FileMode.Create); encoder.Save(fileStream); fileStream.Close(); #endif #if true var anim = new AnimatedGifEncoder(); anim.SetSize(512, 512); anim.SetDelay(200); anim.Start(File.OpenWrite(@"c:\temp\pw_replay.gif")); foreach (var chapters in db.PlanetOwnerHistories.Where(x=>x.Planet.Galaxy.IsDefault).GroupBy(x=>x.Turn).OrderBy(x=>x.Key)) { foreach (var chapter in chapters) ApplyHistoryItem(chapter); mapCanvas.UpdateLayout(); var bitmap = new RenderTargetBitmap(512, 512, 96*512, 96*512, PixelFormats.Pbgra32); bitmap.Render(mapCanvas); var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); var ms = new MemoryStream(); encoder.Save(ms); anim.AddFrame(System.Drawing.Image.FromStream(ms)); } anim.Finish(); #endif }
private void CmdSaveImage() { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"; saveFileDialog1.Title = "Save Screenshot"; saveFileDialog1.FileName = Player.Name; if (saveFileDialog1.ShowDialog() == true) { if (saveFileDialog1.FileName != "") { using (System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile()) { BitmapEncoder encoder; switch (saveFileDialog1.FilterIndex) { default: encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(Screenshot)); break; case 2: encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(Screenshot)); break; case 3: encoder = new GifBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(Screenshot)); break; } encoder.Save(fs); fs.Close(); } } } }
public static void ConvertByteToGIF(BitmapSource imageData, string path) { FileStream stream = new FileStream(path, FileMode.Create); GifBitmapEncoder encoder = new GifBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(imageData)); encoder.Save(stream); encoder = null; stream.Close(); }
/// <summary> /// Crea un archivos animado gif apartir de varios archivos bitmap /// </summary> /// <param name="fout">Ruta de salida del archivo</param> /// <param name="frames">Cada uno de los frames</param> /// <param name="delay">1/100 seg entre frame</param> /// <param name="loops">Número de repeticiones. 0 para infinito, -1 para ninguna</param> public static void CrearGif(string fout, Image[] frames, int delay, int loops) { // ¡¡No funciona con mono!! GifBitmapEncoder encoder = new GifBitmapEncoder(); for (int i = 0; i < frames.Length; i++) { MemoryStream ms = new MemoryStream(); frames[i].Save(ms, System.Drawing.Imaging.ImageFormat.Png); BitmapFrame bf = BitmapFrame.Create(ms); encoder.Frames.Add(bf); } FileStream fs = new FileStream(fout, FileMode.Create); encoder.Save(fs); fs.Close(); fs.Dispose(); ModificarGif(fout, delay, loops); }
/// <summary> /// Returns frames buffer GIF bytes. /// </summary> public byte[] GetStoredFramesGifBytes() { var gifEncoder = new GifBitmapEncoder(); lock (_locker) { var state = CompiledData.DumpGameState(); for (var i = 0; i < _dynamicGameSimulator.Snapshots.Count; ++i) { var rtb = new RenderTargetBitmap((int) GraphicsControl.ActualWidth, (int) GraphicsControl.ActualHeight, 96, 96, PixelFormats.Default); var dv = new DrawingVisual(); CompiledData.SetGameState(_dynamicGameSimulator.Snapshots[i].State); using (var dc = dv.RenderOpen()) { CompiledData.TryInvokeDrawDelegate(dc); } rtb.Render(dv); gifEncoder.Frames.Add(BitmapFrame.Create(rtb)); } CompiledData.SetGameState(state); } byte[] data; using (var stream = new MemoryStream()) { gifEncoder.Save(stream); data = stream.ToArray(); } // Locate the right location where to insert the metadata in the binary // This will be just before the first label 0x0021F9 (Graphic Control Extension) var metadataPtr = -1; for (var i = 0; i < data.Length - 2; ++i) { if (data[i] == 0) { if (data[i + 1] == 0x21) { if (data[i + 2] == 0xF9) { metadataPtr = i; break; } } } } // Set METADATA Repeat // Add an Application Extension Netscape2.0 var appExt = new byte[] { 0x21, 0xFF, 0xB, 0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2E, 0x30, 0x3, 0x1, 0x0, 0x0, 0x0 }; var temp = new byte[data.Length + appExt.Length]; Array.Copy(data, temp, metadataPtr); Array.Copy(appExt, 0, temp, metadataPtr + 1, appExt.Length); Array.Copy(data, metadataPtr + 1, temp, metadataPtr + appExt.Length + 1, data.Length - metadataPtr - 1); data = temp; // Set METADATA frameRate // Sets the third and fourth byte of each Graphic Control Extension (5 bytes from each label 0x0021F9) for (var x = 0; x < data.Length - 3; ++x) { if (data[x] == 0) { if (data[x + 1] == 0x21) { if (data[x + 2] == 0xF9) { if (data[x + 3] == 4) { // word, little endian, the hundredths of second to show this frame var delay = BitConverter.GetBytes(Math.Max(SettingsForm.Instance.DesiredDt/10, 2)); data[x + 5] = delay[0]; data[x + 6] = delay[1]; } } } } } return data; }
/* Paste the page to various types supported by the windows encoder class */ private void PastePage(object sender, RoutedEventArgs e) { var menu = (System.Windows.Controls.MenuItem)sender; String tag = (String)menu.Tag; if (!m_clipboardset || !System.Windows.Clipboard.ContainsImage() || !m_init_done) return; var bitmap = System.Windows.Clipboard.GetImage(); BitmapEncoder encoder; System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog(); dlg.FilterIndex = 1; switch (tag) { case "PNG": dlg.Filter = "PNG Files(*.png)|*.png"; encoder = new PngBitmapEncoder(); break; case "JPG": dlg.Filter = "JPEG Files(*.jpg)|*.jpg"; encoder = new JpegBitmapEncoder(); break; case "WDP": dlg.Filter = "HDP Files(*.wdp)|*.wdp"; encoder = new WmpBitmapEncoder(); break; case "TIF": dlg.Filter = "TIFF Files(*.tif)|*.tif"; encoder = new TiffBitmapEncoder(); break; case "BMP": dlg.Filter = "BMP Files(*.bmp)|*.bmp"; encoder = new BmpBitmapEncoder(); break; case "GIF": dlg.Filter = "GIF Files(*.gif)|*.gif"; encoder = new GifBitmapEncoder(); break; default: return; } encoder.Frames.Add(BitmapFrame.Create(bitmap)); if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (var stream = dlg.OpenFile()) encoder.Save(stream); } }
private void CreateAndShowMainWindow() { // Create the application's main window _mainWindow = new Window {Title = "GIF Imaging Sample"}; var mySv = new ScrollViewer(); var width = 128; var height = width; var stride = width/8; var pixels = new byte[height*stride]; // Define the image palette var myPalette = BitmapPalettes.WebPalette; // Creates a new empty image with the pre-defined palette var image = BitmapSource.Create( width, height, 96, 96, PixelFormats.Indexed1, myPalette, pixels, stride); var stream = new FileStream("new.gif", FileMode.Create); var encoder = new GifBitmapEncoder(); var myTextBlock = new TextBlock {Text = "Codec Author is: " + encoder.CodecInfo.Author}; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(stream); // Open a Stream and decode a GIF image Stream imageStreamSource = new FileStream("tulipfarm.gif", FileMode.Open, FileAccess.Read, FileShare.Read); var decoder = new GifBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource = decoder.Frames[0]; // Draw the Image var myImage = new Image { Source = bitmapSource, Stretch = Stretch.None, Margin = new Thickness(20) }; // Open a Uri and decode a GIF image var myUri = new Uri("tulipfarm.gif", UriKind.RelativeOrAbsolute); var decoder2 = new GifBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); BitmapSource bitmapSource2 = decoder2.Frames[0]; // Draw the Image var myImage2 = new Image { Source = bitmapSource2, Stretch = Stretch.None, Margin = new Thickness(20) }; // Define a StackPanel to host the decoded GIF images var myStackPanel = new StackPanel { Orientation = Orientation.Vertical, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch }; // Add the Image and TextBlock to the parent Grid myStackPanel.Children.Add(myImage); myStackPanel.Children.Add(myImage2); myStackPanel.Children.Add(myTextBlock); // Add the StackPanel as the Content of the Parent Window Object mySv.Content = myStackPanel; _mainWindow.Content = mySv; _mainWindow.Show(); }
/// <summary> /// Image export method /// Encodes a RenderTargetBitmap as a graphic-file (bmp, gif, jpeg, png or tiff) and saves it with the given filename. /// </summary> /// <param name="filename">Filename</param> /// <returns>bool if the export was successfully</returns> /// <author>Thomas Meents, Bernhard Bruns, Andrej Albrecht</author> public bool export(String filename) { try { processModelCanvas.Background = Brushes.White; RenderTargetBitmap render = new RenderTargetBitmap((int)processModelCanvas.Width, (int)processModelCanvas.Height, 96d, 96d, PixelFormats.Pbgra32); render.Clone(); processModelCanvas.Measure(new Size((int)processModelCanvas.Width, (int)processModelCanvas.Height)); processModelCanvas.Arrange(new Rect(new Size((int)processModelCanvas.Width, (int)processModelCanvas.Height))); render.Render(processModelCanvas); switch (this.filetype) { case ".bmp": BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder(); bmpEncoder.Frames.Add(BitmapFrame.Create(render)); using (FileStream bmpFile = File.Create(filename)) { bmpEncoder.Save(bmpFile); } break; case ".gif": GifBitmapEncoder gifEncoder = new GifBitmapEncoder(); gifEncoder.Frames.Add(BitmapFrame.Create(render)); using (FileStream gifFile = File.Create(filename)) { gifEncoder.Save(gifFile); } break; case ".jpeg": JpegBitmapEncoder jpegEncoder = new JpegBitmapEncoder(); jpegEncoder.Frames.Add(BitmapFrame.Create(render)); using (FileStream jpegFile = File.Create(filename)) { jpegEncoder.Save(jpegFile); } break; case ".png": PngBitmapEncoder pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(BitmapFrame.Create(render)); using (FileStream pngFile = File.Create(filename)) { pngEncoder.Save(pngFile); } break; case ".tiff": TiffBitmapEncoder tiffEncoder = new TiffBitmapEncoder(); tiffEncoder.Frames.Add(BitmapFrame.Create(render)); using (FileStream tiffFile = File.Create(filename)) { tiffEncoder.Save(tiffFile); } break; } return true; } catch (Exception) { return false; } }
private void CreateSaveBitmap(Canvas canvas, string filename) { Transform transform = canvas.LayoutTransform; canvas.LayoutTransform = null; // fix margin offset as well Thickness margin = canvas.Margin; Thickness marginOld = canvas.Margin; canvas.Margin = new Thickness(0, 0, 0, 0); RenderTargetBitmap renderBitmap = new RenderTargetBitmap( (int)canvas.Width, (int)canvas.Height, 96d, 96d, PixelFormats.Pbgra32); // needed otherwise the image output is black canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height)); canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height))); renderBitmap.Render(canvas); string strFilExtn = filename.Remove(0, filename.Length - 3); // Save file switch (strFilExtn) { case "bmp": { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); using (FileStream file = File.Create(filename)) { encoder.Save(file); } break; } case "jpg": { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); using (FileStream file = File.Create(filename)) { encoder.Save(file); } break; } case "gif": { GifBitmapEncoder encoder = new GifBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); using (FileStream file = File.Create(filename)) { encoder.Save(file); } break; } case "tif": { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); using (FileStream file = File.Create(filename)) { encoder.Save(file); } break; } case "png": { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); using (FileStream file = File.Create(filename)) { encoder.Save(file); } break; } } canvas.Margin = marginOld; }