public MemoryStream GenerateImage(Visual vsual, int widhth, int height, ImageFormat format) { BitmapEncoder encoder = null; switch (format) { case ImageFormat.JPG : encoder = new JpegBitmapEncoder(); break; case ImageFormat.PNG: encoder = new PngBitmapEncoder(); break; case ImageFormat.BMP: encoder = new BmpBitmapEncoder(); break; case ImageFormat.GIF: encoder = new GifBitmapEncoder(); break; case ImageFormat.TIF: encoder = new TiffBitmapEncoder(); break; } if (encoder == null) return null; RenderTargetBitmap rtb = this.RenderVisaulToBitmap(vsual, widhth, height); MemoryStream file = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(file); return file; }
public void Save(Stream stream, ImageFormat format) { swmi.BitmapEncoder encoder; switch (format) { case ImageFormat.Png: encoder = new swmi.PngBitmapEncoder(); break; case ImageFormat.Gif: encoder = new swmi.GifBitmapEncoder(); break; case ImageFormat.Bitmap: encoder = new swmi.BmpBitmapEncoder(); break; case ImageFormat.Jpeg: encoder = new swmi.JpegBitmapEncoder(); break; case ImageFormat.Tiff: encoder = new swmi.TiffBitmapEncoder(); break; default: throw new NotSupportedException(); } encoder.Frames.Add(swmi.BitmapFrame.Create(FrozenControl)); encoder.Save(stream); }
public static void SaveFixedDocumentAsTiff(FixedDocument document, string outputFileName) { int pages = document.DocumentPaginator.PageCount; TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Ccitt4; for (int pageNum = 0; pageNum < pages; pageNum++) { DocumentPage docPage = document.DocumentPaginator.GetPage(pageNum); RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)(docPage.Size.Width * 300 / 96), (int)(docPage.Size.Height * 300 / 96), 300d, // WPF (Avalon) units are 96dpi based 300d, System.Windows.Media.PixelFormats.Default); renderTarget.Render(docPage.Visual); encoder.Frames.Add(BitmapFrame.Create(renderTarget)); } FileStream outputFileStream = new FileStream(outputFileName, FileMode.Create); encoder.Save(outputFileStream); outputFileStream.Close(); }
private static void SaveBitmap(BitmapSource bitmap, string destination) { BitmapEncoder encoder; switch (Path.GetExtension(destination).ToUpperInvariant()) { case ".BMP": encoder = new BmpBitmapEncoder(); break; case ".GIF": encoder = new GifBitmapEncoder(); break; case ".JPG": encoder = new JpegBitmapEncoder() { QualityLevel = 100 }; break; case ".PNG": encoder = new PngBitmapEncoder(); break; case ".TIF": encoder = new TiffBitmapEncoder() { Compression = TiffCompressOption.Zip }; break; default: throw new NotSupportedException("Not supported output extension."); } encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(new FileStream(destination, FileMode.Create)); }
public void Save(BitmapSource bmSource) { BitmapEncoder encoder; switch (Path.GetExtension(_path).ToLower()) { case ".jpg": case ".jpeg": encoder = new JpegBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".tif": case ".tiff": encoder = new TiffBitmapEncoder(); break; case ".png": encoder = new PngBitmapEncoder(); break; default: throw new ArgumentException("Wrong path"); } encoder.Frames.Add(BitmapFrame.Create(bmSource)); Stream stm = File.Create(_path); encoder.Save(stm); stm.Dispose(); }
private static BitmapEncoder GetBitmapEncoder(ImageContentType imageContentType) { BitmapEncoder bitmapEncoder; switch (imageContentType) { case ImageContentType.ImageBmpContentType: bitmapEncoder = new BmpBitmapEncoder(); break; case ImageContentType.ImageGifContentType: bitmapEncoder = new GifBitmapEncoder(); break; case ImageContentType.ImageJpegContentType: bitmapEncoder = new JpegBitmapEncoder(); break; case ImageContentType.ImageTiffContentType: bitmapEncoder = new TiffBitmapEncoder(); break; case ImageContentType.ImagePngContentType: bitmapEncoder = new PngBitmapEncoder(); break; default: bitmapEncoder = new PngBitmapEncoder(); break; } return bitmapEncoder; }
/// <summary> /// 将一个图像资源使用指定的格式压缩。 /// </summary> /// <param name="imageToConvert"></param> /// <param name="formatOfImage"></param> /// <returns></returns> private byte[] ConvertBitmapSourceToByteArray(System.Windows.Media.Imaging.BitmapSource imageToConvert, System.Drawing.Imaging.ImageFormat formatOfImage) { byte[] buffer; try { using (var ms = new MemoryStream()) { if (System.Drawing.Imaging.ImageFormat.Png == formatOfImage) { var bencoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); bencoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(imageToConvert)); bencoder.Save(ms); } else if (System.Drawing.Imaging.ImageFormat.Tiff == formatOfImage) { var tencoder = new System.Windows.Media.Imaging.TiffBitmapEncoder(); tencoder.Compression = System.Windows.Media.Imaging.TiffCompressOption.Ccitt4; tencoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(imageToConvert)); tencoder.Save(ms); } else { } ms.Flush(); buffer = ms.GetBuffer(); } } catch (Exception) { throw; } return(buffer); }
public static void ToImageFile(this Visual theVisual, string fileName) { BitmapEncoder encoder; switch (Path.GetExtension(fileName).ToLower()) { case ".jpg": case ".jpeg": encoder = new JpegBitmapEncoder(); break; case ".png": encoder = new PngBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".tiff": encoder = new TiffBitmapEncoder(); break; default: throw new EncoderFallbackException("The Specified Filename is not a known image type. Supported image formats are jpeg, png, bmp, gif, and tiff."); } encoder.Frames.Add(BitmapFrame.Create(theVisual.ToBitmapSource())); using (var stream = new FileStream(fileName, FileMode.Create)) encoder.Save(stream); }
public void Save(Stream stream, ImageFormat format) { ApplicationHandler.InvokeIfNecessary(() => { swm.Imaging.BitmapEncoder encoder; switch (format) { case ImageFormat.Png: encoder = new swm.Imaging.PngBitmapEncoder(); break; case ImageFormat.Gif: encoder = new swm.Imaging.GifBitmapEncoder(); break; case ImageFormat.Bitmap: encoder = new swm.Imaging.BmpBitmapEncoder(); break; case ImageFormat.Jpeg: encoder = new swm.Imaging.JpegBitmapEncoder(); break; case ImageFormat.Tiff: encoder = new swm.Imaging.TiffBitmapEncoder(); break; default: throw new NotSupportedException(); } encoder.Frames.Add(swmi.BitmapFrame.Create(Control)); encoder.Save(stream); }); }
public void Save(BitmapSource bmSource) { BitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmSource)); System.IO.Stream strm = new System.IO.MemoryStream(); encoder.Save(strm); strm.Position = 0; Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(strm); image.Save(_path, new Aspose.Imaging.SaveOptions.PsdSaveOptions()); }
public static void CombineTiffs(string DestinationPath, IEnumerable<string> FilePathToMerge, FileMode DestinationPathMode) { //create the file stream to write to the file using (FileStream FileStreamToUse = new FileStream(DestinationPath, DestinationPathMode)) { //create the tiff encoder var Encoder = new TiffBitmapEncoder(); //set the compression Encoder.Compression = TiffCompressOption.Ccitt4; //loop through each of the files to combine foreach (string FileNameToMerge in FilePathToMerge) { try { //declare the bitmap image var ImageToMerge = new BitmapImage(); //start the process ImageToMerge.BeginInit(); //do everything on load ImageToMerge.CacheOption = BitmapCacheOption.OnLoad; //set the file source ImageToMerge.UriSource = new Uri(FileNameToMerge); //we are done and ready to convert ImageToMerge.EndInit(); //convert it now FormatConvertedBitmap ConvertedBitMap = new FormatConvertedBitmap(ImageToMerge, PixelFormats.BlackWhite, BitmapPalettes.BlackAndWhite, 1.0); //create the frames Encoder.Frames.Add(BitmapFrame.Create(ConvertedBitMap)); } catch (NotSupportedException) { //ignore these exception? (means bad image file...or is not a tiff file) throw; } } //save the file Encoder.Save(FileStreamToUse); } }
private static byte[] ConvertToTiffByteArray(BitmapSource bitmap) { var encoder = new TiffBitmapEncoder(); var memoryStream = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); var bytes = ReadFully(memoryStream); return bytes; }
/// <summary> /// Method exports the GraphArea to an png image. /// </summary> /// <param name="surface">GraphArea control</param> /// <param name="path">Image destination path</param> /// <param name="imgdpi">Optional image DPI parameter</param> /// <param name="imgQuality">Optional image quality parameter (for some formats like JPEG)</param> public static void ExportToImage(GraphAreaBase surface, Uri path, ImageType itype, bool useZoomControlSurface = false, double imgdpi = DefaultDPI, int imgQuality = 100) { //Create a render bitmap and push the surface to it Visual vis = surface; if (useZoomControlSurface) { if (surface.Parent != null && surface.Parent is IZoomControl) vis = (surface.Parent as IZoomControl).PresenterVisual; else if(surface.Parent!=null && surface.Parent is FrameworkElement && (surface.Parent as FrameworkElement).Parent is IZoomControl) vis = ((surface.Parent as FrameworkElement).Parent as IZoomControl).PresenterVisual; } var renderBitmap = new RenderTargetBitmap( //(int)surface.ActualWidth, //(int)surface.ActualHeight, (int)(vis as UIElement).DesiredSize.Width + 100, (int)(vis as UIElement).DesiredSize.Height + 100, imgdpi, imgdpi, pixelFormat); //Render the graphlayout onto the bitmap. renderBitmap.Render(vis); //Create a file stream for saving image using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create)) { //Use png encoder for our data BitmapEncoder encoder; switch (itype) { case ImageType.PNG: encoder = new PngBitmapEncoder(); break; case ImageType.JPEG: encoder = new JpegBitmapEncoder() { QualityLevel = imgQuality }; break; case ImageType.BMP: encoder = new BmpBitmapEncoder(); break; case ImageType.GIF: encoder = new GifBitmapEncoder(); break; case ImageType.TIFF: encoder = new TiffBitmapEncoder(); break; default: throw new GX_InvalidDataException("ExportToImage() -> Unknown output image format specified!"); } //Push the rendered bitmap to it encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); //Save the data to the stream encoder.Save(outStream); } }
/// <summary> /// Save a solved map to an image file. /// </summary> /// <param name="path"></param> /// <param name="map"></param> /// <param name="outputPath"></param> public static void OutputBitmap( MapPath path, Map map, string outputPath) { // Get pixels from original map data. byte[] pixels = path.TraceOverMap(map); // Output the bitmap. string extension = Path.GetExtension(outputPath); BitmapEncoder encoder; switch (extension) { default: encoder = new BmpBitmapEncoder(); break; case ".png": encoder = new PngBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".tif": case "tiff": encoder = new TiffBitmapEncoder(); break; case ".jpg": case "jpeg": encoder = new JpegBitmapEncoder(); break; case ".wmp": encoder = new WmpBitmapEncoder(); break; } Console.WriteLine(extension); // TODO: Figure out why files have no compression. int stride = map.Width * Map.BytesPerPixel; BitmapSource bitmapSource = BitmapSource.Create( map.Width, map.Height, 96, 96, PixelFormats.Bgra32, null, pixels, stride); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); using (FileStream filestream = new FileStream(outputPath, FileMode.Create)) { encoder.Save(filestream); } }
public static void ShowExportDialog(this BitmapContainer image) { if (image == null) return; SaveFileDialog saveImg = new SaveFileDialog(); saveImg.Filter = "Jpeg Image|*.jpg|Png Image|*.png|Bitmap Image|*.bmp|Tiff Image|*.tiff|Windows Media Bitmap|*.wmb"; saveImg.Title = "Export Single Image"; saveImg.FileName = image.Name; saveImg.AddExtension = true; saveImg.DefaultExt = "*.png"; saveImg.CheckPathExists = true; BitmapEncoder encoder = null; if (saveImg.ShowDialog() == true) { string ext = Path.GetExtension(saveImg.FileName); switch (ext.ToLower()) { case ".png": encoder = new PngBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".jpeg": case ".jpg": encoder = new JpegBitmapEncoder(); break; case ".tiff": encoder = new TiffBitmapEncoder(); break; case ".wmb": encoder = new WmpBitmapEncoder(); break; default: encoder = new BmpBitmapEncoder(); saveImg.FileName += ".bmp"; break; } encoder.Frames.Add(BitmapFrame.Create(image.Bitmap)); using (FileStream fs = new FileStream(saveImg.FileName, FileMode.OpenOrCreate)) { encoder.Save(fs); fs.Close(); } } }
private void CreateImageFile(FileStream file,BitmapFrame frame,ImageType type) { if(file==null)return; BitmapEncoder encoder=null; switch(type) { case ImageType.Bmp:encoder=new BmpBitmapEncoder();break; case ImageType.Jpg:encoder=new JpegBitmapEncoder(){QualityLevel=100};break; case ImageType.Png:encoder=new PngBitmapEncoder();break; case ImageType.Gif:encoder=new GifBitmapEncoder();break; case ImageType.Tiff:encoder=new TiffBitmapEncoder(){Compression=TiffCompressOption.Default};break; } encoder.Frames.Add(frame); encoder.Save(file); }
private void Button_Click_2(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dialogo1 = new Microsoft.Win32.SaveFileDialog(); // dialogo1.ShowDialog(); dialogo1.AddExtension = false; dialogo1.FileName = temp.host + ".ico"; if (dialogo1.ShowDialog() == true) { FileStream stream5 = new FileStream(dialogo1.FileName, FileMode.Create); TiffBitmapEncoder encoder5 = new TiffBitmapEncoder(); encoder5.Frames.Add(BitmapFrame.Create(temp.imagen)); encoder5.Save(stream5); stream5.Close(); } }
public void SetUpMetadataOnImage(string filename) { string tempName = Path.Combine(Path.GetDirectoryName(filename), Guid.NewGuid().ToString()); // open image file to read using (Stream file = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { // create the decoder for the original file. The BitmapCreateOptions and BitmapCacheOption denote // a lossless transocde. We want to preserve the pixels and cache it on load. Otherwise, we will lose // quality or even not have the file ready when we save, resulting in 0b of data written BitmapDecoder original = BitmapDecoder.Create(file, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); // create an encoder for the output file BitmapEncoder output = null; string ext = Path.GetExtension(filename); switch (ext) { case ".png": output = new PngBitmapEncoder(); break; case ".jpg": output = new JpegBitmapEncoder(); break; case ".tif": output = new TiffBitmapEncoder(); break; } if (original.Frames[0] != null && original.Frames[0].Metadata != null) { // So, we clone the object since it's frozen. BitmapFrame frameCopy = (BitmapFrame)original.Frames[0].Clone(); BitmapMetadata metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata; StripMeta(metadata); // finally, we create a new frame that has all of this new metadata, along with the data that was in the original message output.Frames.Add(BitmapFrame.Create(frameCopy, frameCopy.Thumbnail, metadata, frameCopy.ColorContexts)); } // finally, save the new file over the old file using (Stream outputFile = File.Open(tempName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { output.Save(outputFile); } } File.Delete(filename); File.Move(tempName, filename); }
/// <summary> /// Création d'une image à partir d'une bitmap /// </summary> public static BitmapEncoder CreateImageFromRawData(int ImageWidth, int ImageLength, byte[] ImageData, VideoCellImage.Format videoCellFormat, ref string file_name) { BitmapEncoder encoder = null; int ImageSize = (ImageWidth * ImageLength); byte[] RawData = new byte[ImageSize]; Buffer.BlockCopy(ImageData, ImageWidth * 2, RawData, 0, ImageSize); int bitsPerPixel = 8; int stride = (ImageWidth * bitsPerPixel + 7) / 8; BitmapSource bmps = BitmapSource.Create(ImageWidth, ImageLength , 96, 96 , PixelFormats.Gray8 , null , RawData , stride); switch (videoCellFormat) { case VideoCellImage.Format.JPG: encoder = new JpegBitmapEncoder(); JpegBitmapEncoder encodjpeg = (JpegBitmapEncoder)encoder; encodjpeg.QualityLevel = 10; // Permet de produire des fichiers de taille identique à celle produite par PIL file_name = file_name + ".jpg"; break; case VideoCellImage.Format.TIFF: encoder = new TiffBitmapEncoder(); file_name = file_name + ".tiff"; break; case VideoCellImage.Format.BMP: encoder = new BmpBitmapEncoder(); file_name = file_name + ".bmp"; break; default: break; } encoder.Frames.Add(BitmapFrame.Create(bmps)); return encoder; } // public BitmapEncoder CreateImageFromRawData()
public static void GenerateImage(BitmapSource bitmap, string lowerExtension, Stream destStream) { /* * 参考资料: * [在WPF程序中将控件所呈现的内容保存成图像] * (http://www.cnblogs.com/TianFang/archive/2012/10/07/2714140.html) * [Rendering a WPF Container to Bitmap] * (http://weblog.west-wind.com/posts/2007/Sep/10/Rendering-a-WPF-Container-to-Bitmap) */ BitmapEncoder encoder = null; switch (lowerExtension) { case ".jpg": { encoder = new JpegBitmapEncoder(); break; } case ".png": { encoder = new PngBitmapEncoder(); break; } case ".bmp": { encoder = new BmpBitmapEncoder(); break; } case ".gif": { encoder = new GifBitmapEncoder(); break; } case ".tif": { encoder = new TiffBitmapEncoder(); break; } default: { encoder = new BmpBitmapEncoder(); break; } } encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(destStream); }
/// <summary> /// Convert a <see cref="BitmapSource"/> to a <see cref="BitmapImage"/> /// </summary> /// <param name="source">The original source</param> /// <returns>A <see cref="BitmapImage"/></returns> public static BitmapImage ToBitmapImage(this BitmapSource source) { if (source == null) throw new ArgumentNullException("source"); var encoder = new TiffBitmapEncoder { Compression = TiffCompressOption.None }; var ret = new BitmapImage(); using (var memoryStream = new MemoryStream()) { encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(memoryStream); ret.BeginInit(); ret.StreamSource = new MemoryStream(memoryStream.ToArray()); ret.EndInit(); ret.Freeze(); } return ret; }
private void SaveClicked(object sender, RoutedEventArgs e) { // var dialog = new Microsoft.Win32.SaveFileDialog() { AddExtension = true }; dialog.Filter = "Portable Network Graphics|*.png"; bool? result = dialog.ShowDialog(); if (result.HasValue && result.Value) { try { using(Stream stream = dialog.OpenFile()) { var encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)this.image.Source)); encoder.Save(stream); } this.Close(); } catch(SystemException ex) { MessageBox.Show("Can't save to the file. " + ex.Message, "File Error", MessageBoxButton.OK); } } }
public static void Save(string fileName, List<System.Windows.Controls.Image> imageList) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Ccitt4; foreach (System.Windows.Controls.Image image in imageList) { BitmapSource bitmapSource = (BitmapSource)image.Source; BitmapFrame bitmapFrame = BitmapFrame.Create(bitmapSource); if (bitmapFrame != null) { encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); } } if (encoder.Frames.Count > 0) { FileStream fileStream = new System.IO.FileStream(fileName, FileMode.Create); encoder.Save(fileStream); fileStream.Close(); } else { throw new Exception("No frames in the scanned file encoder."); } }
private void btnSaveImageGraph_Click(object sender, RoutedEventArgs e) { var fileDialog = new SaveFileDialog() { Filter = "PNG (*.png)|*.png|JPEG (*.jpg)|*.jpg|GIF (*.gif)|*.gif|BMP (*.bmp)|*.bmp|TIFF (.tiff)|*.tiff" }; fileDialog.ShowDialog(); if (String.IsNullOrEmpty(fileDialog.FileName)) return; // render it var renderBitmap = new RenderTargetBitmap((int)graphLayout.ActualWidth, (int)graphLayout.ActualHeight, 96d, 96d, PixelFormats.Default); renderBitmap.Render(graphLayout); using (var outStream = new FileStream(fileDialog.FileName, FileMode.Create)) { BitmapEncoder encoder; switch (fileDialog.FilterIndex) { case 1: encoder = new PngBitmapEncoder(); break; case 2: encoder = new JpegBitmapEncoder(); break; case 3: encoder = new GifBitmapEncoder(); break; case 4: encoder = new BmpBitmapEncoder(); break; case 5: encoder = new TiffBitmapEncoder(); break; default: encoder = new PngBitmapEncoder(); break; } encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(outStream); } }
static BitmapEncoder configureTiff(Dictionary<String, Object> options) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); if (options != null) { if (options.ContainsKey("TiffCompression")) { encoder.Compression = (TiffCompressOption)options["TiffCompression"]; } } return (encoder); }
internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat) { try { byte[] result = null; BitmapEncoder encoder = null; switch (preferredFormat.ToLower()) { case ".jpg": case ".jpeg": encoder = new JpegBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".png": encoder = new PngBitmapEncoder(); break; case ".tif": case ".tiff": encoder = new TiffBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".wmp": encoder = new WmpBitmapEncoder(); break; } if (image is BitmapSource) { MemoryStream stream = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource)); encoder.Save(stream); stream.Seek(0, SeekOrigin.Begin); result = new byte[stream.Length]; BinaryReader br = new BinaryReader(stream); br.Read(result, 0, (int)stream.Length); br.Close(); stream.Close(); } return result; } catch (System.Exception ex1) { TaskDialog.Show("Error!", "exception: " + ex1); } return null; }
/// <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; } }
public static byte[] SaveToBytes(this BitmapSource image, ImageType saveType = ImageType.Png) { BitmapEncoder encoder; switch (saveType) { case ImageType.Gif: encoder = new GifBitmapEncoder(); break; case ImageType.Jpg: encoder = new JpegBitmapEncoder(); break; case ImageType.Tiff: encoder = new TiffBitmapEncoder(); break; default: // default: use PNG format encoder = new PngBitmapEncoder(); break; } encoder.Frames.Add(BitmapFrame.Create(image)); using (var ms = new MemoryStream()) { encoder.Save(ms); return ms.ToArray(); } }
public void Scan_NormalPicture_Succeeds(int depth, string mode, string pattern, bool inverted, string outFile) { using (var connection = Connection.At(TestConstants.SaneDaemon)) { using (var device = connection.OpenDevice( TestConstants.UnAuthenticatedDevice)) { var opts = device.AllOptions.ToList(); var pict = opts.First(o => o.Name.Equals("test-picture")); pict.Value = pattern; var cdepth = opts.First(o => o.Name.Equals("depth")); cdepth.Value = depth; var cmode = opts.First(o => o.Name.Equals("mode")); cmode.Value = mode; var inv = opts.First(o => o.Name.Equals("invert-endianess")); if (inv.IsActive) { inv.Value = inverted; } var res = device.Scan(); Assert.That(res.IsError, Is.False, "Error calling scan"); var ours = res.Image.ToBitmapImage(); var theirs = LoadReference(outFile).ToBitmapImage(); bool match = theirs.IsEqual(ours); if (!match) { var failureFile = Path.Combine( TestConstants.FailedTestOutputFolder, outFile) + ".tiff"; var encoder = new TiffBitmapEncoder { Compression = TiffCompressOption.None }; using (var f = File.Create(failureFile)) { encoder.Frames.Add(BitmapFrame.Create(ours)); encoder.Save(f); } } Assert.That(match, Is.True, "Image does not match reference"); } } }
public static void ShowExportMultipleDialog(this IEnumerable<BitmapContainer> images) { SaveFileDialog saveImg = new SaveFileDialog(); saveImg.Filter = "Png Image|*.png|Jpeg Image|*.jpg|Bitmap Image|*.bmp|Tiff Image|*.tiff|Windows Media Bitmap|*.wmb"; saveImg.Title = "Export All Image"; saveImg.FileName = "[Multiple Files - Choose File Type]"; saveImg.AddExtension = false; saveImg.FilterIndex = 0; saveImg.CheckPathExists = true; if (saveImg.ShowDialog() == true) { string ext = saveImg.Filter.Split('|')[saveImg.FilterIndex / 2 + 1].TrimStart('*'); string path = Path.GetDirectoryName(saveImg.FileName); foreach (var bmp in images) { BitmapEncoder encoder = null; switch (ext.ToLower()) { case ".png": encoder = new PngBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".jpeg": case ".jpg": encoder = new JpegBitmapEncoder(); break; case ".tiff": encoder = new TiffBitmapEncoder(); break; case ".wmb": encoder = new WmpBitmapEncoder(); break; default: encoder = new BmpBitmapEncoder(); saveImg.FileName += ".bmp"; break; } encoder.Frames.Add(BitmapFrame.Create(bmp.Bitmap)); using (FileStream fs = new FileStream(Path.Combine(path, bmp.Name + ext), FileMode.OpenOrCreate)) { encoder.Save(fs); fs.Close(); } } } }
public static void SaveXpsReportToTiff(string reportNo) { YellowstonePathology.Business.OrderIdParser orderIdParser = new YellowstonePathology.Business.OrderIdParser(reportNo); string inputFileName = YellowstonePathology.Business.Document.CaseDocument.GetCaseFileNameXPS(orderIdParser); string outputFileName = YellowstonePathology.Business.Document.CaseDocument.GetCaseFileNameTif(orderIdParser); if (File.Exists(inputFileName) == true) { XpsDocument xpsDoc = new XpsDocument(inputFileName, System.IO.FileAccess.Read); FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence(); int pages = docSeq.DocumentPaginator.PageCount; TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Default; encoder.Compression = TiffCompressOption.Ccitt4; for (int pageNum = 0; pageNum < pages; pageNum++) { DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageNum); RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)(docPage.Size.Width * 300 / 96), (int)(docPage.Size.Height * 300 / 96), 300d, 300d, System.Windows.Media.PixelFormats.Default); renderTarget.Render(docPage.Visual); encoder.Frames.Add(BitmapFrame.Create(renderTarget)); } FileStream pageOutStream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write); encoder.Save(pageOutStream); pageOutStream.Close(); xpsDoc.Close(); } }
public static void SaveXpsAsMultiPageTif(string reportNo, object visual) { YellowstonePathology.Business.OrderIdParser orderIdParser = new YellowstonePathology.Business.OrderIdParser(reportNo); string outputFileName = YellowstonePathology.Business.Document.CaseDocument.GetCaseFileNameTif(orderIdParser); FrameworkElement frameworkElement = (FrameworkElement)visual; RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)frameworkElement.ActualWidth, (int)frameworkElement.ActualHeight, 96d, 96d, PixelFormats.Default); renderTargetBitmap.Render(frameworkElement); TiffBitmapEncoder tiffBitmapEncoder = new TiffBitmapEncoder(); tiffBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); using (Stream stream = File.Create(outputFileName)) { tiffBitmapEncoder.Save(stream); } }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { Hp.Drawing drawing = new Hp.Drawing(); if (!DA.GetData <Hp.Drawing>(0, ref drawing)) { return; } int dpi = 96; string path = "C:\\Users\\Public\\Documents\\"; string name = DateTime.UtcNow.ToString("yyyy-dd-M_HH-mm-ss");; int extension = 0; string format = ".png"; bool save = false; if (!DA.GetData(1, ref dpi)) { return; } bool hasPath = DA.GetData(2, ref path); bool hasName = DA.GetData(3, ref name); if (!DA.GetData(4, ref extension)) { return; } if (!DA.GetData(5, ref save)) { return; } Si.BitmapEncoder encoding = new Si.PngBitmapEncoder(); switch (extension) { case 1: encoding = new Si.JpegBitmapEncoder(); format = ".jpeg"; break; case 2: encoding = new Si.BmpBitmapEncoder(); format = ".bmp"; break; case 3: encoding = new Si.TiffBitmapEncoder(); format = ".tiff"; break; case 4: encoding = new Si.GifBitmapEncoder(); format = ".gif"; break; } if (!hasPath) { if (this.OnPingDocument().FilePath != null) { path = Path.GetDirectoryName(this.OnPingDocument().FilePath) + "\\"; } } else { path += "//"; } string filepath = path + name + format; Sm.DrawingVisual dwg = drawing.ToGeometryVisual(); Bitmap bitmap = dwg.ToBitmap(drawing.Width, drawing.Height, dpi, encoding); if (save) { bitmap.Save(filepath); bitmap.Dispose(); } DA.SetData(0, filepath); }
/// <summary> Saves the rendered scoreboard to an image when clicked. </summary> private void SaveImage() { if (MainWindowViewModel.DisplayWindow.IsVisible == false) { MessageBox.Show( "Scoreboard must be showing on-screen in order to save to an image.", "Error: Scoreboard Hidden", MessageBoxButton.OK, MessageBoxImage.Error); return; } const string Filter = "PNG Image (*.png)|*.png|" + "TIFF Image (*.tiff)|*.tiff|" + "All Files (*.*)|*.*"; var sfd = new Microsoft.Win32.SaveFileDialog { Filter = Filter }; if (sfd.ShowDialog() == true) { var filename = sfd.FileName; if (string.IsNullOrEmpty(filename)) { return; } var viewBox = MainWindowViewModel.DisplayWindow.rootGrid; var bmp = new RenderTargetBitmap( (int)viewBox.RenderSize.Width, (int)viewBox.RenderSize.Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(viewBox); BitmapEncoder encoder; var extUpper = Path.GetExtension(filename); if (extUpper == null) { // Could happen if they choose all files and didn't type an extension. MessageBox.Show( "Unrecognized Image Format", "Error: Format Unrecognized", MessageBoxButton.OK, MessageBoxImage.Error); return; } string ext = extUpper.ToLower(); if (ext.Equals(".png")) { encoder = new PngBitmapEncoder(); } else if (ext.Equals(".jpg")) { encoder = new JpegBitmapEncoder { QualityLevel = 95 }; } else if (ext.Equals(".tiff")) { encoder = new TiffBitmapEncoder(); } else if (ext.Equals(".gif")) { encoder = new GifBitmapEncoder(); } else if (ext.Equals(".bmp")) { encoder = new BmpBitmapEncoder(); } else { MessageBox.Show( "Unrecognized Image Format", "Error: Format Unrecognized", MessageBoxButton.OK, MessageBoxImage.Error); return; } using (var stream = new FileStream(filename, FileMode.Create)) { encoder.Frames.Add(BitmapFrame.Create(bmp)); encoder.Save(stream); } } }