static public void Split(string fileName) { using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand); int count = decoder.Frames.Count; for (int _i = 0; _i < count; _i++) { string outName = Path.GetDirectoryName(fileName) + @"\" + Path.GetFileNameWithoutExtension(fileName) + "_PAGE" + _i + Path.GetExtension(fileName); using (FileStream splitFiles = new FileStream(outName, FileMode.Create)) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Ccitt4; List <ColorContext> c = new List <ColorContext>(); c.Add(new ColorContext(System.Windows.Media.PixelFormats.BlackWhite)); encoder.ColorContexts = new System.Collections.ObjectModel.ReadOnlyCollection <ColorContext>(c); encoder.Frames.Add(decoder.Frames[_i]); encoder.Save(splitFiles); } } } return; }
private static void SaveToColor8bitTiff(string filename, uint[,,] imageArray) { if (File.Exists(filename)) { File.Delete(filename); } int width = imageArray.GetLength(0); int height = imageArray.GetLength(1); var array = new Byte[width * height * 3]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { array[j * width * 3 + i * 3] = (byte)imageArray[i, j, 2]; array[j * width * 3 + i * 3 + 1] = (byte)imageArray[i, j, 1]; array[j * width * 3 + i * 3 + 2] = (byte)imageArray[i, j, 0]; } } var bitmapSrc = BitmapSource.Create(width, height, 96, 96, PixelFormats.Rgb24, null, array, 4 * ((width * 3 + 3) / 4)); using (var fs = File.OpenWrite(filename)) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.None; encoder.Frames.Add(BitmapFrame.Create(bitmapSrc)); encoder.Save(fs); fs.Close(); } }
private void GenerateImage(BitmapSource bitmap, ImageFormat format, Stream destStream) { 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; default: throw new InvalidOperationException(); } encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(destStream); }
private static byte[] ExtractXMPPacket(BitmapMetadata xmp) { BitmapMetadata tiffMetaData = new BitmapMetadata("tiff"); tiffMetaData.SetQuery("/ifd/xmp", new BitmapMetadata("xmp")); foreach (string tag in xmp) { object value = xmp.GetQuery(tag); if (value is BitmapMetadata xmpSub) { CopySubIFDRecursive(ref tiffMetaData, xmpSub, "/ifd/xmp" + tag); } else { tiffMetaData.SetQuery("/ifd/xmp" + tag, value); } } byte[] xmpBytes = null; using (MemoryStream stream = new MemoryStream()) { // Create a dummy tiff to extract the XMP packet from. BitmapSource source = BitmapSource.Create(1, 1, 96.0, 96.0, PixelFormats.Gray8, null, new byte[] { 255 }, 1); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source, null, tiffMetaData, null)); encoder.Save(stream); xmpBytes = TiffReader.ExtractXMP(stream); } return(xmpBytes); }
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"); } } }
private static void SaveBmp(Bitmap bmp, string path) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat); var pixelFormats = ConvertBmpPixelFormat(bmp.PixelFormat); BitmapSource source = BitmapSource.Create(bmp.Width, bmp.Height, bmp.HorizontalResolution, bmp.VerticalResolution, pixelFormats, null, bitmapData.Scan0, bitmapData.Stride * bmp.Height, bitmapData.Stride); bmp.UnlockBits(bitmapData); FileStream stream = new FileStream(path, FileMode.Create); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Zip; encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(stream); stream.Close(); }
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 void ZapiszTIFF(object sender, RoutedEventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = "ImageTIFF"; saveFileDialog.Filter = "TIFF (*.tiff)|*.tiff"; if (saveFileDialog.ShowDialog() == true) { try { var encoder = new TiffBitmapEncoder(); BitmapImage obr = new BitmapImage(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)obrazek.Source)); using (var stream = saveFileDialog.OpenFile()) { encoder.Save(stream); } } catch (Exception) { MessageBox.Show("Błąd przy zapisie!", "Zapis do pliku", MessageBoxButton.OK, MessageBoxImage.Warning); } } }
static public void ConvertXPSToTIF(string xpsFileName, string tifFileName) { if (File.Exists(xpsFileName) == true) { XpsDocument xpsDoc = new XpsDocument(xpsFileName, 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(tifFileName, FileMode.Create, FileAccess.Write); encoder.Save(pageOutStream); pageOutStream.Close(); xpsDoc.Close(); } }
private void btn_CopyPixels_Click(object sender, RoutedEventArgs e) { int bpp = bitmap.Format.BitsPerPixel; int stride = (bitmap.PixelWidth * bpp + 7) / 8; int bytesPerPixel = bpp / 8; int areaWidth = (int)(bitmap.PixelWidth / 2); int areaStride = (areaWidth + (areaWidth % 4)) * bytesPerPixel; Int32Rect area = new Int32Rect(0, 0, (int)(bitmap.PixelWidth / 2), bitmap.PixelHeight); //byte[] arry = new byte[imgData.Length]; byte[] imgData = new byte[areaStride * area.Height * bytesPerPixel]; bitmap.CopyPixels(area, imgData, areaStride, 0); //BitmapSource BS = BitmapSource.Create(bitmap.PixelWidth, bitmap.PixelHeight, bitmap.DpiX, bitmap.DpiY, bitmap.Format, bitmap.Palette, imgData, stride); BitmapSource BS = BitmapSource.Create(area.Width, area.Height, bitmap.DpiX, bitmap.DpiY, bitmap.Format, bitmap.Palette, imgData, areaStride); //Encode Output Image from Array TiffBitmapEncoder encoder = new TiffBitmapEncoder(); MemoryStream memoryStream = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(BS)); encoder.Save(memoryStream); BitmapImage tempImg = new BitmapImage(); memoryStream.Position = 0; tempImg.BeginInit(); tempImg.StreamSource = new MemoryStream(memoryStream.ToArray()); //new MemoryStream(memoryStream.ToArray()); tempImg.EndInit(); memoryStream.Close(); ImageControl2.Source = tempImg; }
public static void SaveTiff(string path, Int16[] pixels, int w, int h) { int width = w; int height = h; int stride = w * sizeof(Int16); // Define the image palette BitmapPalette myPalette = BitmapPalettes.BlackAndWhite; // Creates a new empty image with the pre-defined palette BitmapSource image = BitmapSource.Create( width, height, 100, 100, System.Windows.Media.PixelFormats.Gray16, myPalette, pixels, stride); System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Create); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); TextBlock myTextBlock = new TextBlock(); myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString(); encoder.Compression = TiffCompressOption.None; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(stream); stream.Close(); }
public static void SlipTiffFile(string file) { // 画像ファイルデータをStreamで開く using (FileStream imageFileStrm = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { // BitmapDecoderを作成する BitmapDecoder decoder = BitmapDecoder.Create(imageFileStrm, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); // ページ数を取得する int pageCount = decoder.Frames.Count; for (int iLoop = 0; iLoop < pageCount; iLoop++) { // ページを選択する BitmapFrame bmpFrame = decoder.Frames[iLoop]; // BmpBitmapEncoderを作成する TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Lzw; // ページに追加する encoder.Frames.Add(bmpFrame); string pagefileName = System.IO.Path.GetFileNameWithoutExtension(file) + "_" + iLoop + ".tif"; string filePath = Path.Combine(Path.GetDirectoryName(file), pagefileName); // シーケンスフォルダへ出力 using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { encoder.Save(fs); } } } }
/// <summary> /// Forward application of the algorithm /// </summary> /// <param name="parOriginalImage">Original image stream</param> /// <param name="parArguments">List of an arguments (int compression)</param> /// <returns>Compressed image stream</returns> public override Stream CompressImage(Stream parOriginalImage, List <object> parArguments) { Stream result = new MemoryStream(); Bitmap original = new Bitmap(parOriginalImage); int compression = (int)parArguments[0]; if (compression == 7) { original.Save(result, ImageFormat.Tiff); } else { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = (TiffCompressOption)compression; BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( original.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); WriteableBitmap writableBitmap = new WriteableBitmap(bitmapSource); encoder.Frames.Add(BitmapFrame.Create(writableBitmap)); encoder.Save(result); } return(result); }
public static void CreateTiff(string _fileName, int dpi, FrameworkElement element) { //Mesuse and Create the right size of the Element element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); element.Arrange(new Rect(new Point(0, 0), element.DesiredSize)); //Convert width and height to whole pixels var width = (int)Math.Ceiling(element.ActualWidth); var height = (int)Math.Ceiling(element.ActualHeight); width = width == 0 ? 1 : width; height = height == 0 ? 1 : height; var bitmap = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Default); //Render the Visual bitmap.Render(element); if (_fileName != string.Empty) { using var stream = new FileStream(_fileName, FileMode.Create); var encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); //Save the bitmap encoder.Save(stream); //Close the stream stream.Close(); } }
/// <summary> /// Saves the RenderTargetBitmap passed to the outputStream supplied /// in TIFF format. /// </summary> /// <param name="src">A RenderTargetBitmap containing the image data to save.</param> /// <param name="outputStream">A Stream used as the output stream to /// write the image data to.</param> public static void saveAsBmp(RenderTargetBitmap src, Stream outputStream) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(src)); encoder.Save(outputStream); }
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."); } }
public static void SaveImageRaster3DAsTIFF3D2(string save_path, IImageRaster <IRaster3DInteger, uint> image) { Stream destination_stream = new FileStream(save_path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.None; for (int index_z = 0; index_z < image.Raster.Size2; index_z++) { Bitmap bitmap = ConvertToBitmapUInt16(image, index_z); BitmapSource bitmap_source = ToolsRendering.CreateBitmapSourceFromBitmap16Bit(bitmap); encoder.Frames.Add(BitmapFrame.Create(bitmap_source)); } encoder.Save(destination_stream); //TiffBitmapEncoder encoder = new TiffBitmapEncoder(destination_stream_, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); //Stream imageStreamSource = new FileStream(load_path, FileMode.Open, FileAccess.Read, FileShare.Read); //TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); //BitmapSource test_frame = decoder.Frames[0]; //int size_x = test_frame.PixelWidth; //int size_y = test_frame.PixelHeight; //int size_z = decoder.Frames.Count; //int bits_per_pixel = test_frame.Format.BitsPerPixel; //for (int index_z = 0; index_z < size_z; index_z++) //{ // // save each frame to a bytestream // BitmapSource frame = decoder.Frames[index_z]; // // img.CopyPixels(pixels, stride, 0) // MemoryStream byte_stream = new MemoryStream(); // // bitmap.Save(byte_stream, ImageFormat.Tiff); // // and then create a new Image from it // System.Drawing.Image image = System.Drawing.Image.FromStream(byte_stream); // // d //} }
public void RotateTiffImage(string filePath, double rotation) { BitmapFrame transformed; using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = fileStream; bitmap.EndInit(); bitmap.Freeze(); TransformedBitmap transformedBitmap = new TransformedBitmap(bitmap, new RotateTransform(rotation)); transformedBitmap.Freeze(); transformed = BitmapFrame.Create(transformedBitmap); transformed.Freeze(); } // ファイルを書き換えないとファイルサイズが増大するので一度削除 FileInfo fi = new FileInfo(filePath); fi.Delete(); using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write)) { TiffBitmapEncoder tiffEncoder = new TiffBitmapEncoder(); tiffEncoder.Frames.Add(transformed); tiffEncoder.Save(fileStream); } }
public void SaveAs16BitBitmap(string path) { var bmp = To16BitBitmap(); var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); var bitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat); var source = BitmapSource.Create(bmp.Width, bmp.Height, bmp.HorizontalResolution, bmp.VerticalResolution, PixelFormats.Gray16, null, bitmapData.Scan0, bitmapData.Stride * bmp.Height, bitmapData.Stride); bmp.UnlockBits(bitmapData); using (var stream = new FileStream(path, FileMode.Create)) { var encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.None; encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(stream); stream.Close(); } }
/// <summary>画像データを縮小する</summary> /// <param name="refStream">画像データ</param> /// <param name="imageSize">画像の最大サイズ</param> private static void ShrinkImageData(ref MemoryStream refStream, int imageSize = 128) { long streamPosition = refStream.Position; var srcImage = BitmapFrame.Create(refStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); if (srcImage.PixelWidth <= imageSize && srcImage.PixelHeight <= imageSize) { refStream.Position = streamPosition; return; } double maxScale = Math.Min( imageSize / (double)srcImage.PixelWidth, imageSize / (double)srcImage.PixelHeight); var destImage = ResizeImage(srcImage, maxScale); var imageStream = new MemoryStream(); System.Diagnostics.Debug.WriteLine($"[{nameof(ProfileImageCache)}] Image resized. width: {destImage.PixelWidth}, height: {destImage.PixelHeight}"); var encoder = new TiffBitmapEncoder { Compression = TiffCompressOption.Default, Frames = new BitmapFrame[] { BitmapFrame.Create(destImage) }, }; encoder.Save(imageStream); refStream.Dispose(); imageStream.Position = 0; refStream = imageStream; }
/// <summary> /// Exports the PDF pages as Tiff Images. /// </summary> /// <param name="fileName">The PDF file name</param> private void ExportPDFtoTiff(string fileName) { PdfDocumentView pdfViewer = new PdfDocumentView(); //Load the input PDF file pdfViewer.Load(fileName); //Export the images From the input PDF file at the page range of 0 to 1 . BitmapSource[] image = pdfViewer.ExportAsImage(0, pdfViewer.PageCount - 1); if (image != null) { for (int i = 0; i < image.Length; i++) { //Initialize the new Tiff bitmap encoder TiffBitmapEncoder encoder = new TiffBitmapEncoder(); //Set the compression to zip to reduce the file size. encoder.Compression = TiffCompressOption.Zip; //Create the bitmap frame using the bitmap source and add it to the encoder. encoder.Frames.Add(BitmapFrame.Create(image[i])); //Create the file stream for the output in the desired image format. using (FileStream stream = new FileStream("Image_" + i.ToString() + ".Tiff", FileMode.Create)) { //Save the stream, so that the image will be generated in the output location. encoder.Save(stream); } } } }
/// <summary> /// 保存图像 /// </summary> /// <param name="savePath">图像保存路径</param> /// <param name="BS">控件源</param> /// <param name="extName">文件拓展名</param> public static void SaveImage(string savePath, BitmapSource BS, string extName) { BitmapEncoder encoder = null; switch (extName) { case ".png": encoder = new PngBitmapEncoder(); break; case ".jpg": encoder = new JpegBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".tiff": encoder = new TiffBitmapEncoder(); break; default: throw new InvalidOperationException(); } encoder.Frames.Add(BitmapFrame.Create(BS)); encoder.Save(File.Create(savePath)); }
/// <summary> /// 将指定位图保存到指定路径中 /// </summary> /// <param name="bitmap">要保存的位图</param> /// <param name="path">要保存到的路径(包含文件名和扩展卡名)</param> public static void Save(BitmapSource bitmap, string path) { BitmapEncoder encoder = null; string fileExtension = System.IO.Path.GetExtension(path).ToUpper(); //选取编码器 switch (fileExtension) { case ".BMP": encoder = new BmpBitmapEncoder(); break; case ".GIF": encoder = new GifBitmapEncoder(); break; case ".JPEG": encoder = new JpegBitmapEncoder(); break; case ".PNG": encoder = new PngBitmapEncoder(); break; case ".TIFF": encoder = new TiffBitmapEncoder(); break; default: throw new Exception("无法识别的图像格式!"); } encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (var file = File.Create(path)) encoder.Save(file); }
private static void SaveToGrayscaleTiff(string filename, uint[,] imageArray) { if (File.Exists(filename)) { File.Delete(filename); } int width = imageArray.GetLength(0); int height = imageArray.GetLength(1); var array = new ushort[width * height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { array[j * width + i] = (ushort)imageArray[i, j]; } } var bitmapSrc = BitmapSource.Create(width, height, 96, 96, PixelFormats.Gray16, null, array, 4 * ((width * 2 + 3) / 4)); using (var fs = File.OpenWrite(filename)) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.None; encoder.Frames.Add(BitmapFrame.Create(bitmapSrc)); encoder.Save(fs); fs.Close(); } }
private static BitmapSource?ChooseOrEncodeWindowIcon(BitmapSource?smallIcon, BitmapSource?largeIcon) { BitmapSource?bitmapSource = null; if (largeIcon != null) { if (smallIcon != null) { BitmapFrame bitmapFrame; var tiffBitmapEncoder = new TiffBitmapEncoder(); tiffBitmapEncoder.Frames.Add(BitmapFrame.Create(smallIcon)); tiffBitmapEncoder.Frames.Add(BitmapFrame.Create(largeIcon)); using (var memoryStream = new MemoryStream()) { tiffBitmapEncoder.Save(memoryStream); bitmapFrame = BitmapFrame.Create(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } FreezeImage(bitmapFrame); bitmapSource = bitmapFrame; } else { bitmapSource = largeIcon; } } else if (smallIcon != null) { bitmapSource = smallIcon; } return(bitmapSource); }
public void SaveToTIF(string fileName) { XpsDocument xd = new XpsDocument(fileName, System.IO.FileAccess.Read); FixedDocumentSequence fds = xd.GetFixedDocumentSequence(); DocumentPaginator paginator = fds.DocumentPaginator; System.Windows.Media.Visual visual = paginator.GetPage(0).Visual; System.Windows.FrameworkElement fe = (System.Windows.FrameworkElement)visual; int multiplyFactor = 4; string outputPath = fileName.Replace(".xps", ".tif"); RenderTargetBitmap bmp = new RenderTargetBitmap( (int)fe.ActualWidth * multiplyFactor, (int)fe.ActualHeight * multiplyFactor, 96d * multiplyFactor, 96d * multiplyFactor, System.Windows.Media.PixelFormats.Default); bmp.Render(fe); TiffBitmapEncoder tff = new TiffBitmapEncoder(); tff.Frames.Add(BitmapFrame.Create(bmp)); using (Stream stream = File.Create(outputPath)) { tff.Save(stream); } }
private void button_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog(); sfd.Filter = "图片文件|*.bmp"; if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } InkCanvas ink = this.inkCanvas; string path = sfd.FileName; FileStream fs = new FileStream(path, FileMode.Create); //文件流对象 //RenderTargetBitmap用来创建一副位图对象 RenderTargetBitmap rtb = new RenderTargetBitmap((int)ink.ActualWidth, (int)ink.ActualHeight, 1 / 100, 1 / 100, PixelFormats.Default); rtb.Render(ink); //呈现位图对象 //BitmapEncoder用来保存BitmapFrame对象,并保存为指定的文件 //BitmapFrame是图像数据 BitmapEncoder be = new TiffBitmapEncoder(); //指定格式 be.Frames.Add(BitmapFrame.Create(rtb)); be.Save(fs); fs.Close(); }
/// <summary> /// Loads the PNG XMP meta data using a dummy TIFF. /// </summary> /// <param name="xmp">The XMP string to load.</param> /// <returns>The loaded XMP block, or null.</returns> private static BitmapMetadata LoadPNGMetadata(string xmp) { BitmapMetadata xmpData = null; using (MemoryStream stream = new MemoryStream()) { // PNG stores the XMP meta-data in an iTXt chunk as an UTF8 encoded string, // so we have to save it to a dummy tiff and grab the XMP meta-data on load. BitmapMetadata tiffMetadata = new BitmapMetadata("tiff"); tiffMetadata.SetQuery("/ifd/xmp", new BitmapMetadata("xmp")); tiffMetadata.SetQuery("/ifd/xmp", Encoding.UTF8.GetBytes(xmp)); BitmapSource source = BitmapSource.Create(1, 1, 96.0, 96.0, PixelFormats.Gray8, null, new byte[] { 255 }, 1); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source, null, tiffMetadata, null)); encoder.Save(stream); TiffBitmapDecoder dec = new TiffBitmapDecoder(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); if (dec.Frames.Count == 1) { BitmapMetadata meta = dec.Frames[0].Metadata as BitmapMetadata; if (meta != null) { xmpData = meta.GetQuery("/ifd/xmp") as BitmapMetadata; } } } return(xmpData); }
/// <summary> /// /// </summary> /// <param name="image"></param> /// <param name="pagesToRemove"></param> /// <returns></returns> public static Stream RemovePagesFromImageStream(Stream image, IEnumerable <int> pagesToRemove) { MemoryStream write = new MemoryStream(); Dictionary <int, int> pages = (pagesToRemove == null) ? new Dictionary <int, int>() : pagesToRemove.ToDictionary(p => p); TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Ccitt4; TiffBitmapDecoder decoder; decoder = new TiffBitmapDecoder(image, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnDemand); int frames = decoder.Frames.Count; for (int i = 0; i < frames; i++) { if (pages.ContainsKey(i) == true) { continue; } encoder.Frames.Add(decoder.Frames[i]); } encoder.Save(write); return(write); }