Пример #1
1
        private double[] getFeatures()
        {
            rtb = new RenderTargetBitmap((int)InkCanvas1.ActualWidth, (int)InkCanvas1.ActualHeight,
                96d, 96d, PixelFormats.Default);

            rtb.Render(InkCanvas1);

            //save the ink to a memory stream
            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(rtb));

            byte[] bitmapBytes;
            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                ms.Position = 0;
                bitmapBytes = ms.ToArray();

                ms.Seek(0, SeekOrigin.Begin);
                bmp = new Bitmap(ms);
            }

            bmp = resize.Apply(bmp);

            double[] features = ToFeatures(bmp);

            return features;
        }
Пример #2
0
        /// <summary>
        /// Saves the full chart to a file, including technical analysis.
        /// </summary>
        /// <param name="filename">The file to write to.</param>
        public void SaveAsImage(string filename)
        {
            if (string.IsNullOrEmpty(filename))
                throw new ArgumentNullException();

            var extension = Path.GetExtension(filename);
            if (string.IsNullOrEmpty(extension))
                throw new ArgumentNullException();

            BitmapEncoder bitmapEncoder;
            extension = extension.ToLower();
            if (extension == ".png")
                bitmapEncoder = new PngBitmapEncoder();
            else if (extension == ".jpg" || extension == ".jpeg")
                bitmapEncoder = new JpegBitmapEncoder();
            else if (extension == ".gif")
                bitmapEncoder = new GifBitmapEncoder();
            else if (extension == ".bmp")
                bitmapEncoder = new BmpBitmapEncoder();
            else throw new ArgumentException("Cannot find a BitmapEncoder for this file type.");

            var renderTargetBitmap = new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Pbgra32);

            foreach (var child in LogicalTreeHelper.GetChildren(this))
            {
                if (child is ChartPanel)
                    renderTargetBitmap.Render((ChartPanel)child);
            }

            bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
            using (Stream stream = File.Create(filename))
            {
                bitmapEncoder.Save(stream);
            }
        }
Пример #3
0
 /// <summary>
 /// Renders a visual UI element to a stream in bitmap (BMP) format</summary>
 /// <param name="visual">Visual UI element to be rendered</param>
 /// <param name="stream">Stream data written to</param>
 /// <param name="scale">Rendering scale</param>
 public static void RenderToBmp(this UIElement visual, Stream stream, double scale)
 {
     BitmapFrame frame = visual.RenderToBitmapFrame(scale);
     var encoder = new BmpBitmapEncoder();
     encoder.Frames.Add(frame);
     encoder.Save(stream);
 }
Пример #4
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);
            });
        }
Пример #5
0
        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;
        }
Пример #6
0
        private void InsertMessageAction(object parameter)
        {
            string message = parameter as string;

            MemoryStream ms = new MemoryStream();
            BitmapEncoder encode = new BmpBitmapEncoder();

            encode.Frames.Add(BitmapFrame.Create(_sourceImage));
            encode.Save(ms);
            var bmpData = ms.ToArray();
            BitmapManipulator manipulator = new BitmapManipulator(bmpData);
            string encryptedMessage = Cryptography.Encrypt(message, this.Password);
            manipulator.InsertMessage(encryptedMessage);

            var imageSource = new BitmapImage();
            MemoryStream imageMS = new MemoryStream(manipulator.Bytes);

            imageSource.BeginInit();
            imageSource.StreamSource = imageMS;
            imageSource.EndInit();

            CryptedImage = imageSource;
            if (bmpData.Length != manipulator.Bytes.Length)
            {
                Debugger.Break();
            }

        }
Пример #7
0
        public override void Buid(string imageName)
        {
            if(imageName == null) return;

            Panel.Measure(new Size((int)Panel.Width, (int)Panel.Height));
            Panel.Arrange(new Rect(new Size((int)Panel.Width, (int)Panel.Height)));

            int height = (int)Panel.Height;
            int width = (int)Panel.Width;

            RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(Panel);

            string extension = Path.GetExtension(imageName)?.ToLower();

            BitmapEncoder encoder;
            if (extension == ".bmp")
                encoder = new BmpBitmapEncoder();
            else if (extension == ".png")
                encoder = new PngBitmapEncoder();
            else if (extension == ".jpg")
                encoder = new JpegBitmapEncoder();
            else
                return;

            encoder.Frames.Add(BitmapFrame.Create(bmp));

            using (Stream stm = File.Create(imageName))
            {
                encoder.Save(stm);
            }
        }
        private BitmapSource RefreshZoomedImage(System.Windows.Point pt)
        {
            using (var screenBmp = new Bitmap(
                       80,
                       80,
                       System.Drawing.Imaging.PixelFormat.Format32bppArgb))
            {
                MemoryStream ms      = new MemoryStream();
                var          encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
                encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(this.screenImage.Source as System.Windows.Media.Imaging.BitmapSource));
                encoder.Save(ms);
                ms.Flush();

                using (var bmpGraphics = Graphics.FromImage(System.Drawing.Image.FromStream(ms)))
                {
                    bmpGraphics.CopyFromScreen((int)pt.X, (int)pt.Y, 0, 0, screenBmp.Size);
                    return(Imaging.CreateBitmapSourceFromHBitmap(
                               screenBmp.GetHbitmap(),
                               IntPtr.Zero,
                               Int32Rect.Empty,
                               BitmapSizeOptions.FromEmptyOptions()));
                }
            }

            //CroppedBitmap cp = new CroppedBitmap(this.screenImage.Source as BitmapSource, new Int32Rect((int)pt.X, (int)pt.Y, 80, 80));
            //cp.
        }
        public static void Save(this BitmapSource image, string filePath, ImageFormat format)
        {
            BitmapEncoder encoder = null;
            
            switch(format)
            {
                case ImageFormat.Png:
                    encoder = new PngBitmapEncoder();
                    break;
                case ImageFormat.Jpeg:
                    encoder = new JpegBitmapEncoder();
                    break;
                case ImageFormat.Bmp:
                    encoder = new BmpBitmapEncoder();
                    break;
            }

            if (encoder == null) 
                return;

            encoder.Frames.Add(BitmapFrame.Create(BitmapFrame.Create(image)));

            using (var stream = new FileStream(filePath, FileMode.Create))
                encoder.Save(stream);
        }
Пример #10
0
 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();
 }
Пример #11
0
        public Document CreatePdfDocument(Chart chart, string path)
        {
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
                (int) chart.ActualWidth,
                (int) chart.ActualHeight,
                96d,
                96d,
                PixelFormats.Pbgra32);

            renderBitmap.Render(chart);

            MemoryStream stream = new MemoryStream();
            BitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            encoder.Save(stream);

            Bitmap bitmap = new Bitmap(stream);
            System.Drawing.Image image = bitmap;

            System.Drawing.Image resizedImage = ResizeImage(image, image.Width*2, image.Height);

            Document doc = new Document(PageSize.A4);
            PdfWriter.GetInstance(doc, new FileStream(path, FileMode.OpenOrCreate));
            doc.Open();
            Image pdfImage = Image.GetInstance(resizedImage, ImageFormat.Jpeg);
            doc.Add(pdfImage);
            doc.Close();
            
            return doc;
        }
Пример #12
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));
        }
Пример #13
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);
        }
Пример #14
0
        public static void Initialize(dynamic window)
        {
            Bitmap icon;
            using (MemoryStream outStream = new MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(new Uri(@"pack://*****:*****@"Exit"};
            tsm.Click += (sender, e) =>
            {
                Exit();
            };
            cms.Items.Add(tsm);
            _notifyIcon.ContextMenuStrip = cms;

            Window = window;
        }
Пример #15
0
        // Handles save image click
        private void OnSaveImageClick(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "24-bit Bitmap (*.bmp)|*.bmp|JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF (*.gif)|*.gif|PNG (*.png)|*.png";
            dlg.FilterIndex = 4;
            bool? dlgResult = dlg.ShowDialog(Window.GetWindow(this));
            if(dlgResult.HasValue && dlgResult.Value)
            {
                Visualizer visualizer = Visualizer;
                RenderTargetBitmap bitmap = new RenderTargetBitmap((int)previewPage.PageWidth, (int)previewPage.PageHeight, 96, 96, PixelFormats.Pbgra32);

                visualizer.RenderTo(bitmap);

                BitmapEncoder encoder = null;
                string ext = System.IO.Path.GetExtension(dlg.FileName);
                if (ext == "bmp") encoder = new BmpBitmapEncoder();
                else if ((ext == "jpg") || (ext == "jpeg")) encoder = new JpegBitmapEncoder();
                else encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                using (FileStream stream = new FileStream(dlg.FileName, FileMode.Create, FileAccess.Write))
                {
                    encoder.Save(stream);
                    stream.Flush();
                }
            }
        }
Пример #16
0
        public static bool ToFile(BitmapSource source, string s_uri)
        {
            if (source != null)
            {
                System.IO.File.Delete(s_uri);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                BmpBitmapEncoder bmpenco = new BmpBitmapEncoder();
                bmpenco.Frames.Add(BitmapFrame.Create(source));
                bmpenco.Save(ms);
                ms.Flush();
                
                System.IO.Stream st = System.IO.File.Open(s_uri, System.IO.FileMode.CreateNew);
                st.Write(ms.GetBuffer(), 0, ms.ToArray().Length);
                
                st.Close();
                st.Dispose();

                ms.Dispose();
                return true;
            }
            else
            {
                return false;
            }
        }
Пример #17
0
        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;
        }
Пример #18
0
        public static System.Drawing.Bitmap BMPFromBitmapSource(BitmapSource source, int iCount)
        {
            //int width = 128;
            //int height = 128;
            //int stride = width;
            //byte[] pixels = new byte[height * stride];

            //// Define the image palette
            //BitmapPalette myPalette = BitmapPalettes.Halftone256;

            //// Creates a new empty image with the pre-defined palette

            //BitmapSource image = BitmapSource.Create(
            //    width,
            //    height,
            //    96,
            //    96,
            //    PixelFormats.Indexed8,
            //    myPalette,
            //    pixels,
            //    stride);

            FileStream stream = new FileStream("image" + iCount + ".BMP", FileMode.Create);
            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            //TextBlock myTextBlock = new TextBlock();
            //myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
            //encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(source));
            encoder.Save(stream);

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
            return bitmap;
        }
Пример #19
0
        private void InsertImageIntoRange(ImageSource source, Excel.Worksheet currentSheet, Excel.Range range, int maxHeight = -1)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(source as System.Windows.Media.Imaging.BitmapSource));
            encoder.Save(ms);
            ms.Flush();

            System.Windows.Forms.Clipboard.SetDataObject(System.Drawing.Image.FromStream(ms), true);
            currentSheet.Paste(range);

            // Resize image to fit range
            Excel.Shape shape = (Excel.Shape)currentSheet.Shapes.Item(currentSheet.Shapes.Count);
            shape.LockAspectRatio = Office.MsoTriState.msoCTrue;

            if (maxHeight == -1)
            {
                shape.Height = (int)range.Height;
            }
            else
            {
                shape.Height = (int)((source.Height / (double)maxHeight) * range.Height);
            }

            shape.Line.Visible = Office.MsoTriState.msoTrue;
            ms.Close();
        }
Пример #20
0
        public static BitmapImage Bitmap2BitmapImage(System.Drawing.Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            BitmapSource bmpSource;
            BitmapImage bitmapImage = new BitmapImage();

            try
            {
                bmpSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                             hBitmap,
                             IntPtr.Zero,
                             Int32Rect.Empty,
                             BitmapSizeOptions.FromEmptyOptions());

                BitmapEncoder enc = new BmpBitmapEncoder();
                MemoryStream memoryStream = new MemoryStream();

                enc.Frames.Add(BitmapFrame.Create(bmpSource));
                enc.Save(memoryStream);

                memoryStream.Position = 0;
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memoryStream;
                bitmapImage.EndInit();
            }
            finally
            {
                DeleteObject(hBitmap);
            }

            return bitmapImage;
        }
 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);
 }
Пример #22
0
        /// <summary>
        /// Converts ImageSource to byte[]
        /// </summary>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        /// <param name="value">The value that is produced by the binding target.</param><param name="targetType">The type to convert to.</param><param name="parameter">The converter parameter to use.</param><param name="culture">The culture to use in the converter.</param>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var renderTargetBitmap = value as RenderTargetBitmap;
            if (null != renderTargetBitmap)
            {
                var bitmapImage = new BitmapImage();
                var bitmapEncoder = new BmpBitmapEncoder();
                bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));

                using (var stream = new MemoryStream())
                {
                    bitmapEncoder.Save(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.StreamSource = stream;
                    bitmapImage.EndInit();
                }
                var encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
                byte[] data = null;
                using (var ms = new MemoryStream())
                {
                    encoder.Save(ms);
                    data = ms.ToArray();
                }
                return data;
            }
            return null;
        }
Пример #23
0
        private void LoadImage(string imgPathOrg)
        {
            BitmapImage bmpImgPrc = new BitmapImage(); // デコードされたビットマップイメージのインスタンスを作る。

            try
            {
                // 一度解像度を整えて、固定パスに出力
                System.Drawing.Bitmap bmp = null;
                {
                    BitmapImage bmpImgSrc = new BitmapImage();
                    bmpImgSrc.BeginInit();
                    bmpImgSrc.UriSource = new Uri(imgPathOrg); // ビットマップイメージのソースにファイルを指定する。
                    bmpImgSrc.EndInit();

                    var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
                    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmpImgSrc));
                    using (var ms = new System.IO.MemoryStream())
                    {
                        encoder.Save(ms);
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
                        using (var temp = new System.Drawing.Bitmap(ms))
                        {
                            // このおまじないの意味は参考資料を参照
                            bmp = new System.Drawing.Bitmap(temp);
                        }
                    }
                }
                // 解像度設定
                bmp.SetResolution(96, 96);

                // 一度固定ファイルとして保存
                imgPath = System.IO.Path.GetDirectoryName(imgPathOrg) + "\\_tmp.jpg";
                bmp.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bmp.Dispose();

                //  再読込
                bmpImgPrc.BeginInit();
                bmpImgPrc.UriSource = new Uri(imgPath); // ビットマップイメージのソースにファイルを指定する。
                bmpImgPrc.EndInit();


                ImageBrush imageBrush = new ImageBrush();
                imageBrush.ImageSource = bmpImgPrc;
                imageBrush.Stretch     = Stretch.None;
                imageBrush.AlignmentX  = AlignmentX.Left;
                imageBrush.AlignmentY  = AlignmentY.Top;

                imgSize.Width  = bmpImgPrc.PixelWidth;
                imgSize.Height = bmpImgPrc.PixelHeight;

                canvas.Background = imageBrush; // Imageコントロールにバインディングする。

                this.Title = System.IO.Path.GetFileName(imgPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #24
0
 /// <summary>
 /// Save the BitmapImage img to the File filename as a .bmp
 /// </summary>
 /// <param name="img"></param>
 /// <param name="fileName"></param>
 public static void SaveToBmp(BitmapImage img, string fileName)
 {
     var encoder = new BmpBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(img));
     using (var filestream = new FileStream(fileName, FileMode.Create))
     {
         encoder.Save(filestream);
     }
 }
Пример #25
0
        public static void ExportToImage(FrameworkElement surface)
        {
            Size size = new Size(surface.ActualWidth, surface.ActualHeight);
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);
            renderBitmap.Render(surface);

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = DateTime.Now.ToString("yyyy-M-d-H_m_s");
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\WLANFolder";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            dlg.InitialDirectory = path;
            dlg.OverwritePrompt = true;
            dlg.Filter = "JPEG Image|*.jpg|Bitmap Image|*.bmp|PNG Image|*.png";
            dlg.Title = "Save an Image File";
            dlg.ShowDialog();
            dlg.RestoreDirectory = true;

            if (dlg.FileName != "")
            {
                try
                {
                    using(FileStream outStream = (System.IO.FileStream)dlg.OpenFile())
                    {
                        switch (dlg.FilterIndex)
                        {
                            case 1:
                                {
                                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                                    encoder.Save(outStream);
                                }
                                break;
                            case 2:
                                {
                                    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                                    encoder.Save(outStream);
                                }
                                break;
                            case 3:
                                {
                                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                                    encoder.Save(outStream);
                                }
                                break;
                            default:
                                break;
                        }
                        System.Diagnostics.Process.Start(dlg.FileName);
                    }          
                }
                catch (ArgumentException)
                { return; }
            }
        }
Пример #26
0
 public static Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
 {
     using (var outStream = new MemoryStream()) {
         BitmapEncoder enc = new BmpBitmapEncoder();
         enc.Frames.Add(BitmapFrame.Create(bitmapImage));
         enc.Save(outStream);
         var bitmap = new Bitmap(outStream);
         return new Bitmap(bitmap);
     }
 }
 public static Bitmap BitmapFromSource(this BitmapSource bitmapsource)
 {
     // do not close stream cuz bitmap become invalid.
     // TODO: possible memory leakage? dunno. investigate.
     var outStream = new MemoryStream();
     BitmapEncoder enc = new BmpBitmapEncoder();
     enc.Frames.Add(BitmapFrame.Create(bitmapsource));
     enc.Save(outStream);
     return new Bitmap(outStream);
 }
Пример #28
0
        public static Stream ToStream(BitmapSource bitmap)
        {
            var memory = new MemoryStream();

            var encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(memory);

            return memory;
        }
Пример #29
0
        public static System.Drawing.Image ImageWpfToGDI(System.Windows.Media.ImageSource imageSource)
        {
            MemoryStream ms = new MemoryStream();
            var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(imageSource as System.Windows.Media.Imaging.BitmapSource));
            encoder.Save(ms);
            ms.Flush();

            return System.Drawing.Image.FromStream(ms);
        }
Пример #30
0
        private static MemoryStream GetBmpStream(BitmapFrame photo)
        {
            MemoryStream result = new MemoryStream();

            BmpBitmapEncoder targetEncoder = new BmpBitmapEncoder();
            targetEncoder.Frames.Add(photo);
            targetEncoder.Save(result);

            return result;
        }
Пример #31
0
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            MemoryStream ms = new MemoryStream();
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create((BitmapImage)value));
            enc.Save(ms);
            Bitmap bitmap = new Bitmap(ms);

            return new Bitmap(bitmap);
        }
Пример #32
0
 //-------------------------------------
 private Bitmap BitmapImage2Bitmap(ref BitmapImage bitmapImage)
 {
     using (MemoryStream outStream = new MemoryStream())
     {
         BitmapEncoder enc = new BmpBitmapEncoder();
         enc.Frames.Add(BitmapFrame.Create(bitmapImage));
         enc.Save(outStream);
         return new Bitmap(outStream);
     }
 }
Пример #33
0
        private System.Drawing.Image ImageWpfToGDI(BitmapSource image)
        {
            MemoryStream ms      = new MemoryStream();
            var          encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image));
            encoder.Save(ms);
            ms.Flush();
            return(System.Drawing.Image.FromStream(ms));
        }
 /// <summary>
 /// Converts the given BitmapSource into a Bitmap.
 /// </summary>
 /// <param name="This">This BitmapSource.</param>
 /// <returns>The copy of the BitmapSource as a Bitmap-Instance.</returns>
 public static Bitmap AsBitmap(this BitmapSource This) {
   Contract.Requires(This != null);
   using (var memoryStream = new IO.MemoryStream()) {
     var bitmapEncoder = new BmpBitmapEncoder();
     bitmapEncoder.Frames.Add(BitmapFrame.Create(This));
     bitmapEncoder.Save(memoryStream);
     using (var temp = new Bitmap(memoryStream))
       return (new Bitmap(temp));
   }
 }
Пример #35
0
        private void SaveRTBAsBMP(RenderTargetBitmap bmp, string filename)
        {
            var enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();

            enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));

            using (var stm = File.Create(filename))
            {
                enc.Save(stm);
            }
        }
Пример #36
0
 public static System.Drawing.Image AsGdiPlusImage(this System.Windows.Media.ImageSource image)
 {
     using (MemoryStream memoryStream = new MemoryStream())
     {
         var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
         encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image as System.Windows.Media.Imaging.BitmapSource));
         encoder.Save(memoryStream);
         memoryStream.Flush();
         return(System.Drawing.Image.FromStream(memoryStream));
     }
 }
Пример #37
0
 public static Bitmap GetBitmapFromBitmapSource(BitmapSource bSource)
 {
     Bitmap bmp;
       using (MemoryStream ms = new MemoryStream()) {
     BitmapEncoder enc = new BmpBitmapEncoder();
     enc.Frames.Add(BitmapFrame.Create(bSource));
     enc.Save(ms);
     bmp = new Bitmap(ms);
       }
       return bmp;
 }
Пример #38
0
 private static System.Drawing.Image ImageSourceToGDI(BitmapSource src)
 {
     using (var ms = new MemoryStream())
     {
         var encoder = new BmpBitmapEncoder();
         encoder.Frames.Add(BitmapFrame.Create(src));
         encoder.Save(ms);
         ms.Flush();
         return System.Drawing.Image.FromStream(ms);
     }
 }
Пример #39
0
        public static Bitmap ToWinFormsBitmap(this System.Windows.Media.Imaging.BitmapSource bitmapsource)
        {
            using (MemoryStream stream = new MemoryStream()) {
                System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
                enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapsource));
                enc.Save(stream);

                using (Bitmap tempBitmap = new Bitmap(stream)) {
                    return(new Bitmap(tempBitmap));
                }
            }
        }
        /// <summary>
        /// Show image out side passing.
        /// source: https://stackoverflow.com/questions/6484357/converting-bitmapimage-to-bitmap-and-vice-versa
        /// </summary>
        /// <param name="Disp"></param>
        private static void ShowImage(System.Windows.Media.Imaging.BitmapImage Disp)
        {
            using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
            {
                System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
                enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(Disp));
                enc.Save(outStream);
                SrcImg = new System.Drawing.Bitmap(outStream);

                pbCtrl.Disp(SrcImg);
            }
        }
        private void ShowImage(System.Windows.Media.Imaging.BitmapImage Disp)
        {
            System.Drawing.Bitmap DisplayImg;
            using (System.IO.MemoryStream outStream = new System.IO.MemoryStream())
            {
                System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
                enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(Disp));
                enc.Save(outStream);
                DisplayImg = new System.Drawing.Bitmap(outStream);

                pctbxDisp.Image = DisplayImg;
            }
        }
Пример #42
0
        private static void SendBitmap(System.Windows.Media.Imaging.BitmapSource b)
        {
            ClipboardPacket packet = new ClipboardPacket();

            packet.type = (byte)ClipboardPacketType.BITMAP;
            packet.name = String.Empty;

            MemoryStream ms = new MemoryStream();

            System.Windows.Media.Imaging.BmpBitmapEncoder encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
            System.Windows.Media.Imaging.BitmapImage      bImg    = new System.Windows.Media.Imaging.BitmapImage();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(b));
            encoder.Save(ms);
            byte[] getBitmapData = ms.ToArray();

            int maxPayloadLen = ClipboardConstants.MaxPacketPayloadLength;

            packet.payloadLength = maxPayloadLen;
            packet.totalLength   = ms.Length;

            long bytesToSend = ms.Length;

            while (bytesToSend > 0)
            {
                if (bytesToSend < maxPayloadLen)
                {
                    packet.payloadLength = (int)bytesToSend;
                }
                packet.payload = new byte[maxPayloadLen];
                Array.Copy(getBitmapData, ms.Length - bytesToSend, packet.payload, 0, packet.payloadLength);
                bytesToSend -= packet.payloadLength;
                byte[] toSend = Serialization.GetClipboardBytes(packet);
                Utility.SendBytes(socket, toSend, toSend.Length, SocketFlags.None);
            }
            ms.Close();
        }
Пример #43
0
        private static BitmapSource SharpenFixedByCanvas(BitmapSource input, int width, int height)
        {
            if (input.PixelWidth == width && input.PixelHeight == height)
            {
                return(input);
            }

            if (input.Format != PixelFormats.Bgra32 || input.Format != PixelFormats.Pbgra32)
            {
                input = new FormatConvertedBitmap(input, PixelFormats.Bgra32, null, 0);
            }

            //Use the same scale for x and y to keep aspect ratio.
            double scale = Math.Min((double)width / input.PixelWidth, height / (double)input.PixelHeight);

            int x = (int)Math.Round((width - (input.PixelWidth * scale)) / 2);
            int y = (int)Math.Round((height - (input.PixelHeight * scale)) / 2);

            var scaled = new TransformedBitmap(input, new ScaleTransform(scale, scale));
            var stride = scaled.PixelWidth * (scaled.Format.BitsPerPixel / 8);

            #region Make a WhiteCanvas
            List <System.Windows.Media.Color> colors = new List <System.Windows.Media.Color>();
            colors.Add(System.Windows.Media.Colors.White);

            BitmapPalette palette = new BitmapPalette(colors);
            System.Windows.Media.PixelFormat pf =
                System.Windows.Media.PixelFormats.Indexed1;
            int strideWhite = width / pf.BitsPerPixel;

            byte[] pixels = new byte[height * strideWhite];

            for (int i = 0; i < height * strideWhite; ++i)
            {
                pixels[i] = 0x00;
            }
            BitmapSource whiteimage = BitmapSource.Create(
                width,
                height,
                96,
                96,
                pf,
                palette,
                pixels,
                strideWhite);

            #endregion

            #region ResizeImage + WhiteCanvas
            // Create a render bitmap and push the surface to it
            var target        = new RenderTargetBitmap(width, height, whiteimage.DpiX, whiteimage.DpiY, PixelFormats.Default);
            var targetVisual  = new DrawingVisual();
            var targetContext = targetVisual.RenderOpen();
            //targetContext.DrawImage(scaled, new System.Windows.Rect(0, 0, scaled.Width, scaled.Height));            //ImageDrawing
            targetContext.DrawImage(scaled, new System.Windows.Rect(0, 0, scaled.PixelWidth, scaled.PixelHeight));    //ImageDrawing
            targetContext.Close();
            target.Render(targetVisual);

            // Adding those two render bitmap to the same drawing visual
            var            resultBitmap = new RenderTargetBitmap(width, height, whiteimage.DpiX, whiteimage.DpiY, PixelFormats.Default);
            DrawingVisual  dv           = new DrawingVisual();
            DrawingContext dc           = dv.RenderOpen();
            dc.DrawImage(whiteimage, new System.Windows.Rect(0, 0, width, height));
            int posTx = (whiteimage.PixelWidth - scaled.PixelWidth) / 2;
            int posTy = (whiteimage.PixelHeight - scaled.PixelHeight) / 2;
            dc.DrawImage(target, new System.Windows.Rect(posTx, posTy, width, height));
            dc.Close();
            resultBitmap.Render(dv);
            #endregion

            #region MediaBitmap to DrawingBitmap - Result Image
            MemoryStream ms      = new MemoryStream();
            var          encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(resultBitmap));
            encoder.Save(ms);
            ms.Flush();
            System.Drawing.Image gdiImage = System.Drawing.Image.FromStream(ms);
            #endregion

            return(ToBitmapImage(ApplySharpen((double)width, (System.Drawing.Bitmap)gdiImage)));  //ShapenImage

            //return scaled;
            //return resultBitmap;
        }
Пример #44
0
        /// <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);
        }