Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        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));
        }
        /// <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);
 }
Ejemplo n.º 5
0
        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);
            });
        }
Ejemplo n.º 6
0
 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());
 }
Ejemplo n.º 7
0
        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);
            }
        }
Ejemplo n.º 8
0
        /// <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);
            }
        }
Ejemplo n.º 9
0
 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();
                    }
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        /// <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;
        }
Ejemplo n.º 13
0
 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);
         }
     }
 }
Ejemplo n.º 14
0
        public static void SaveTiff(BitmapSource source, string fileName, int dpi, TiffCompressOption compression)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (String.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName");
            //if (File.Exists(fileName)) File.Delete(fileName);

            BitmapMetadata metadata = GetBitmapMetadata("tiff");

            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Compression = compression;
                encoder.Frames.Add(BitmapFrame.Create(source, null, metadata, null));
                encoder.Save(fs);
                fs.Close();
            }
        }
Ejemplo n.º 15
0
        private void saveImageAsFile(System.Drawing.Image img)
        {
            string extension = readExtension(savePathTxt.Text);

            switch (extension)
            {
                case ".jpeg":
                    var JPEGenc = new JpegBitmapEncoder();
                    JPEGenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img)));
                    using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write))
                    {
                        JPEGenc.Save(stream);
                    }
                    break;
                case ".jpg":
                    var JPGenc = new JpegBitmapEncoder();
                    JPGenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img)));
                    using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write))
                    {
                        JPGenc.Save(stream);
                    }
                    break;
                case ".png":
                    var PNGenc = new PngBitmapEncoder();
                    PNGenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img)));
                    using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write))
                    {
                        PNGenc.Save(stream);
                    }
                    break;

                case ".tif":
                    var TIFenc = new TiffBitmapEncoder();
                    // get TIFF compression type
                    if (tifTypeCBX.SelectedIndex == 0)
                    {
                        TIFenc.Compression = TiffCompressOption.Ccitt3;
                    }
                    if (tifTypeCBX.SelectedIndex == 1)
                    {
                        TIFenc.Compression = TiffCompressOption.Ccitt4;
                    }
                    if (tifTypeCBX.SelectedIndex == 2)
                    {
                        TIFenc.Compression = TiffCompressOption.Lzw;
                    }
                    if (tifTypeCBX.SelectedIndex == 3)
                    {
                        TIFenc.Compression = TiffCompressOption.None;
                    }
                    if (tifTypeCBX.SelectedIndex == 4)
                    {
                        TIFenc.Compression = TiffCompressOption.Rle;
                    }
                    if (tifTypeCBX.SelectedIndex == 5)
                    {
                        TIFenc.Compression = TiffCompressOption.Zip;
                    }
                    TIFenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img)));
                    using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write))
                    {
                        TIFenc.Save(stream);
                    }
                    break;
                case ".tiff":
                    var TIFFenc = new TiffBitmapEncoder();
                    // get TIFF compression type
                    if (tifTypeCBX.SelectedIndex == 0)
                    {
                        TIFFenc.Compression = TiffCompressOption.Ccitt3;
                    }
                    if (tifTypeCBX.SelectedIndex == 1)
                    {
                        TIFFenc.Compression = TiffCompressOption.Ccitt4;
                    }
                    if (tifTypeCBX.SelectedIndex == 2)
                    {
                        TIFFenc.Compression = TiffCompressOption.Lzw;
                    }
                    if (tifTypeCBX.SelectedIndex == 3)
                    {
                        TIFFenc.Compression = TiffCompressOption.None;
                    }
                    if (tifTypeCBX.SelectedIndex == 4)
                    {
                        TIFFenc.Compression = TiffCompressOption.Rle;
                    }
                    if (tifTypeCBX.SelectedIndex == 5)
                    {
                        TIFFenc.Compression = TiffCompressOption.Zip;
                    }
                    TIFFenc.Frames.Add(BitmapFrame.Create(ImageProc.ImgToBmpSource(img)));
                    using (var stream = new FileStream(savePathTxt.Text, FileMode.Create, FileAccess.Write))
                    {
                        TIFFenc.Save(stream);
                    }
                    break;
            }
        }
Ejemplo n.º 16
0
 private void SaveBMP(string file)
 {
     var fs = File.Create(file);
     var bmp = new RenderTargetBitmap((int)grif.ActualWidth, (int)grif.ActualHeight + 20, 1 / 32, 1 / 32, PixelFormats.Pbgra32);
     bmp.Render(grif);
     var encoder = new TiffBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(bmp));
     encoder.Save(fs);
     fs.Close();
 }
Ejemplo n.º 17
0
        /// <summary>
        /// 视频截取第一帧
        /// </summary>
        /// <param name="videopath">要截屏的视频路径</param>
        /// <param name="savepath">要把截屏保存到得路径</param>
        /// <param name="rect">截屏所得图片框大小</param>
        public static void GetVideoThumb(string videopath, string savepath, Rect rect)
        {
            //打开视频
            MediaPlayer _player = new MediaPlayer();
            _player.Volume = 0;
            _player.Open(new Uri(videopath));
            _player.Play();

            //截取视频第一帧
            Thread.Sleep(1300);
            RenderTargetBitmap target = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 1 / 100, 1 / 100, PixelFormats.Pbgra32);
            DrawingVisual visual = new DrawingVisual();
            DrawingContext context = visual.RenderOpen();
            context.DrawVideo(_player, new Rect(0, 0, (int)rect.Width, (int)rect.Height));
            context.Close();

            target.Render(visual);

            //移除视频
            _player.Stop();
            _player.Position = TimeSpan.FromSeconds(0);
            _player.Close();
            _player = null;

            //保存第一帧
            BitmapEncoder encoder = new TiffBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(target));

            FileStream fs = new FileStream(savepath, FileMode.Create);
            encoder.Save(fs);
            fs.Close();
        }
Ejemplo n.º 18
0
        private void SaveImagePrintBtn_Click(object sender, RoutedEventArgs e)
        {
            SaveImagePopup.IsOpen = false;
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.Filter = "Bitmap files (*.bmp)|*.bmp|Jpeg files (*.jpg)|*.jpg|Tiff files (*.tif)|*.tif|PNG files (*.png)|*.png";
            dlg.AddExtension = true;
            dlg.DefaultExt = "jpg";
            dlg.FilterIndex = 2;
            BitmapEncoder be;
            FileStream fs;
            if (dlg.ShowDialog() == true)//System.Windows.Forms.DialogResult.OK)
            {
                var bsource = MainImage.Source as BitmapSource;
                BitmapSource bms = XRayImageRenderer.GetRenderedXrayImage(bsource,
                                        m_SourceObject,
                                        m_ViewObject,
                                        (ShaderEffect)XrayImage_Panel.Effect,
                                        GetListOfEffects(),
                                        bsource.Width,
                                        bsource.Height,
                                        _AdornerLayerManager,
                                        ImagePreview.IsAnnotationShown,
                                        ImagePreview.IsMeasurementShown);

                string fname = dlg.FileName;
                string ext = System.IO.Path.GetExtension(fname).ToLower();

                fs = new FileStream(fname, FileMode.Create);
                switch (ext)
                {
                    case ".bmp":
                        be = new BmpBitmapEncoder();
                        be.Frames.Add(BitmapFrame.Create(bms));
                        be.Save(fs);
                        break;
                    case ".jpg":
                        be = new JpegBitmapEncoder();
                        be.Frames.Add(BitmapFrame.Create(bms));
                        be.Save(fs);
                        break;
                    case ".png":
                        be = new PngBitmapEncoder();
                        be.Frames.Add(BitmapFrame.Create(bms));
                        be.Save(fs);
                        break;
                    case ".tif":
                        be = new TiffBitmapEncoder();
                        be.Frames.Add(BitmapFrame.Create(bms));
                        be.Save(fs);
                        break;
                }
                fs.Close();
            }
        }
Ejemplo n.º 19
0
        internal static byte[] SaveWithCodecs(byte[] imageData, ImageEngineFormat format, int width, int height, AlphaSettings alphaSetting)
        {
            var image = UsefulThings.WPF.Images.CreateWriteableBitmap(imageData, width, height);
            image.Freeze();
            BitmapFrame frame = null;

            if (alphaSetting == AlphaSettings.RemoveAlphaChannel)
                frame = BitmapFrame.Create(new FormatConvertedBitmap(image, PixelFormats.Bgr32, image.Palette, 0));
            else
                frame = BitmapFrame.Create(image);

            frame.Freeze();

            // KFreon: Choose encoder based on desired format.
            BitmapEncoder encoder = null;
            int estimatedImageSize = 0;

            int estimateHeaderSize = 1024;
            switch (format)
            {
                case ImageEngineFormat.BMP:
                    encoder = new BmpBitmapEncoder();
                    estimatedImageSize = estimateHeaderSize + width * height * 4;  // Fairly good estimation
                    break;
                case ImageEngineFormat.JPG:
                    encoder = new JpegBitmapEncoder();
                    ((JpegBitmapEncoder)encoder).QualityLevel = JPGCompressionSetting;
                    estimatedImageSize = estimateHeaderSize + width * height / 6;  // Estimation
                    break;
                case ImageEngineFormat.PNG:
                    encoder = new PngBitmapEncoder();
                    estimatedImageSize = estimateHeaderSize + width * height / 2;  // Estimation
                    break;
                case ImageEngineFormat.GIF:
                    encoder = new GifBitmapEncoder();
                    estimatedImageSize = estimateHeaderSize + width * height / 5;  // Estimation
                    break;
                case ImageEngineFormat.TIF:
                    encoder = new TiffBitmapEncoder();
                    estimatedImageSize = estimateHeaderSize + width * height; // Esimation
                    break;
                default:
                    throw new InvalidOperationException($"Unable to encode format: {format} using Windows 8.1 Codecs.");
            }

            encoder.Frames.Add(frame);
            using (MemoryStream ms = new MemoryStream(estimatedImageSize))  // Big enough to reduce memory copying.
            {
                encoder.Save(ms);
                return ms.ToArray();
            }
        }
Ejemplo n.º 20
0
        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();
        }
        public void Convert()
        {
            try
            {
                BitmapDecoder bmpDec = BitmapDecoder.Create(new Uri(m_filePath), BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.OnLoad);
                BitmapSource srs = bmpDec.Frames[0];

                if (Path.GetExtension(m_convertedFilePath).Equals(".tif", StringComparison.CurrentCultureIgnoreCase))
                {
                    using (FileStream stream = new FileStream(m_convertedFilePath, FileMode.Create, FileAccess.Write, FileShare.Delete))
                    {
                        TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                        encoder.Compression = TiffCompressOption.None;
                        encoder.Frames.Add(BitmapFrame.Create(srs));
                        encoder.Save(stream);
                    }
                }

            }
            catch (Exception ex)
            {
                Framework.ShowError("Unable to save the temporary file at: " + m_convertedFilePath, true);
            }
        }
Ejemplo n.º 22
0
        private static void Snap(string filename, ushort[] data, int width)
        {
            var tempWritableBitmap = new WriteableBitmap(width, data.Length / width, 96, 96, PixelFormats.Gray16, null);
            tempWritableBitmap.Lock();
            Marshal.Copy(Array.ConvertAll(data, s => (short)s), 0, tempWritableBitmap.BackBuffer, data.Length);
            tempWritableBitmap.AddDirtyRect(new Int32Rect(0, 0, width, data.Length / width));
            tempWritableBitmap.Unlock();

            var encoder = new TiffBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(tempWritableBitmap));
            var filestream = File.Open(filename, FileMode.OpenOrCreate);
            encoder.Save(filestream);
            filestream.Close();
        }
Ejemplo n.º 23
0
        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
            saveFileDialog1.Title = "Save an Image File";
            saveFileDialog1.ShowDialog();




            if (saveFileDialog1.FileName != "")
            {
                FileStream stream = new FileStream(saveFileDialog1.FileName, FileMode.Create);


                TiffBitmapEncoder encoder = new TiffBitmapEncoder();

                //   var bitmap = BitmapFrame.Create(  );
                //  TextBlock myTextBlock = new TextBlock();
                //   myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
                //    bitmap = image.Source;

                //var bitmap = BitmapFrame();
                //2. Create an Image control which will accept the DrawingImage as its Source
                System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
                myImage.Source = image.Source;
                myImage.Arrange(new Rect(0, 0, 500, 500));  //Required

                //3. Render the Image control's content to a RenderTargetBitmap
                RenderTargetBitmap rtb = new RenderTargetBitmap(500, 500, 96, 96, System.Windows.Media.PixelFormats.Default);
                rtb.Render(myImage);

                //4. Now the RenderTargetBitmap can be used with the JpegBitmapEncoder
                encoder.Frames.Add(BitmapFrame.Create(rtb));
                //    MessageBox.Show(myPalette.Colors.Count.ToString());
                encoder.Save(stream);


                stream.Close();
            }
        }
Ejemplo n.º 24
0
        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");
                }
            }
        }
Ejemplo n.º 25
0
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".tif;";
            dlg.Filter = "Image Files (*.tif)|*.tif";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                FileStream fileStream = new FileStream( dlg.FileName ,  FileMode.Create );
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Compression = TiffCompressOption.Lzw;
                encoder.Frames.Add(BitmapFrame.Create( (BitmapSource) p_result.Source ));
                encoder.Save(fileStream);
                fileStream.Close();

            }
        }
Ejemplo n.º 26
0
        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);
            }
        }
Ejemplo n.º 27
0
 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.");
     }
 }
Ejemplo n.º 28
0
        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();
            }
        }
Ejemplo n.º 29
0
 public override void Write(Stream file, ImageData image)
 {
     var encoder = new TiffBitmapEncoder();
     encoder.Compression = TiffCompressOption.Zip;
     encoder.Frames.Add (BitmapFrame.Create (image.Bitmap, null, null, null));
     encoder.Save (file);
 }
Ejemplo n.º 30
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {Title = "TIFF 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.tif", FileMode.Create);
            var encoder = new TiffBitmapEncoder();
            var myTextBlock = new TextBlock {Text = "Codec Author is: " + encoder.CodecInfo.Author};
            encoder.Compression = TiffCompressOption.Zip;
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);

            // Open a Stream and decode a TIFF image
            Stream imageStreamSource = new FileStream("tulipfarm.tif", FileMode.Open, FileAccess.Read, FileShare.Read);
            var decoder = new TiffBitmapDecoder(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 TIFF image
            var myUri = new Uri("tulipfarm.tif", UriKind.RelativeOrAbsolute);
            var decoder2 = new TiffBitmapDecoder(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 TIFF 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();
        }
Ejemplo n.º 31
0
 public void SaveImageToFile(string path)
 {
     string extension = Path.GetExtension(path).ToLower();
     DrawingVisual dv = new DrawingVisual();
     using (DrawingContext dc = dv.RenderOpen())
     {
         if (extension == ".bmp" || extension == "jpg")
         {
             dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, Math.Ceiling(Width + Location.X * 2), Math.Ceiling(Width + Location.Y * 2)));
         }
         ActiveChild.DrawEquation(dc);
     }
     RenderTargetBitmap bitmap = new RenderTargetBitmap((int)(Math.Ceiling(Width + Location.X * 2)), (int)(Math.Ceiling(Height + Location.Y * 2)), 96, 96, PixelFormats.Default);
     bitmap.Render(dv);
     BitmapEncoder encoder = null;
     switch (extension)
     {
         case ".jpg":
             encoder = new JpegBitmapEncoder();
             break;
         case ".gif":
             encoder = new GifBitmapEncoder();
             break;
         case ".bmp":
             encoder = new BmpBitmapEncoder();
             break;
         case ".png":
             encoder = new PngBitmapEncoder();
             break;
         case ".wdp":
             encoder = new WmpBitmapEncoder();
             break;
         case ".tif":
             encoder = new TiffBitmapEncoder();
             break;
     }
     try
     {
         encoder.Frames.Add(BitmapFrame.Create(bitmap));
         using (Stream s = File.Create(path))
         {
             encoder.Save(s);
         }
     }
     catch
     {
         MessageBox.Show("File could not be saved. Please make sure the path you entered is correct", "Error");
     }
 }
        /// <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;
            }
        }
Ejemplo n.º 33
0
        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;
        }