private void Create3DViewPort()
        {
            var hvp3d = new HelixViewport3D();
            Viewport3D vp3d = new Viewport3D();
            var lights = new DefaultLights();
            var tp = new Teapot();

            hvp3d.Children.Add(lights);
            hvp3d.Children.Add(tp);

            vp3d = hvp3d.Viewport;
            tata.Children.Add(vp3d); // comenter ca pour test

            /* MEGA TEST DE L'ESPACE SUBSAHARIEN */

            RenderTargetBitmap bmp = new RenderTargetBitmap(800, 800, 96, 96, PixelFormats.Pbgra32);
            var rect = new Rect(0, 0, 800, 800);
            vp3d.Measure(new Size(800, 800));
            vp3d.Arrange(rect);
            vp3d.InvalidateVisual();
            
            bmp.Render(vp3d);

            PngBitmapEncoder png = new PngBitmapEncoder();
            png.Frames.Add(BitmapFrame.Create(bmp));

            String filepath = "C:\\Users\\Remi\\Desktop\\canardmasque.png";
            using (Stream stm = File.Create(filepath))
            {
                png.Save(stm);
            }
        }
예제 #2
2
        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            var rect = new Rect { Width = 512, Height = 384 };
            var dv = new DrawingVisual();

            var dc = dv.RenderOpen();
            dc.PushTransform(new TranslateTransform(-rect.X, -rect.Y));
            dc.DrawRectangle(InkCanvasMain.Background, null, rect);
            InkCanvasMain.Strokes.Draw(dc);
            dc.Close();

            var rtb = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default);
            rtb.Render(dv);
            var enc = new PngBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(rtb));

            var fn = TextBoxFileName.Text;
            if (!fn.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) fn += ".png";
            using (Stream s = File.Create(TegakiImageFolder + "/" + fn))
            {
                enc.Save(s);
            }
            ((TegakiWindowViewModel)DataContext).AddToMediaList(System.IO.Path.GetFullPath(TegakiImageFolder + "/" + fn));
            Close();
        }
예제 #3
0
        public static void SaveAsImage(FrameworkElement visual)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".png";
            dlg.Filter = "PNG Image (.png)|*.png|JPEG Image (.jpg)|*.jpg";

            if (dlg.ShowDialog().Value)
            {
                BitmapSource img = (BitmapSource)ToImageSource(visual);

                FileStream stream = new FileStream(dlg.FileName, FileMode.Create);
                BitmapEncoder encoder = null; // new BitmapEncoder();

                if (dlg.SafeFileName.ToLower().EndsWith(".png"))
                {
                    encoder = new PngBitmapEncoder();
                }
                else
                {
                    encoder = new JpegBitmapEncoder();
                }

                encoder.Frames.Add(BitmapFrame.Create(img));
                encoder.Save(stream);
                stream.Close();
            }
        }
예제 #4
0
        public static void ExportToFile(BitmapSource graphBitmap)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            const int FilterIndexJpeg = 1;
            const int FilterIndexPng = 2;
            saveDialog.Filter = "JPEG|*.jpg|PNG|*.png";
            saveDialog.Title = "Save Graph As";
            saveDialog.AddExtension = true;
            saveDialog.ShowDialog();

            if (string.IsNullOrEmpty(saveDialog.FileName))
            {
                return;
            }

            using (FileStream fileStream = (FileStream)saveDialog.OpenFile())
            {
                BitmapEncoder bitmapEncoder;

                switch (saveDialog.FilterIndex)
                {
                    case FilterIndexJpeg:
                        bitmapEncoder = new JpegBitmapEncoder();
                        break;
                    case FilterIndexPng:
                        bitmapEncoder = new PngBitmapEncoder();
                        break;
                    default:
                        throw new ArgumentException("Invalid file save type");
                }

                bitmapEncoder.Frames.Add(BitmapFrame.Create(graphBitmap));
                bitmapEncoder.Save(fileStream);
            }
        }
예제 #5
0
        public static byte[] ExportToPng(this FrameworkElement surface)
        {
            var transform = surface.LayoutTransform;
            surface.LayoutTransform = null;

            var size = new Size(surface.ActualWidth, surface.ActualHeight);
            surface.Measure(size);
            surface.Arrange(new Rect(size));

            var renderBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);
            renderBitmap.Render(surface);

            try
            {
                using (var outStream = new MemoryStream())
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                    encoder.Save(outStream);
                    return outStream.ToArray();
                }
            }
            finally 
            {
                surface.LayoutTransform = transform;
            }
        }
예제 #6
0
		/// <summary>
		///     Преобразует XAML Drawing/DrawingGroup в png base64 string
		/// </summary>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="drawing"></param>
		/// <returns>Base64 string containing png bitmap</returns>
		public static string XamlDrawingToPngBase64String(int width, int height, Drawing drawing) {
			var bitmapEncoder = new PngBitmapEncoder();
			// The image parameters...
			double dpiX = 96;
			double dpiY = 96;

			// The Visual to use as the source of the RenderTargetBitmap.
			var drawingVisual = new DrawingVisual();
			using (var drawingContext = drawingVisual.RenderOpen()) {
				drawingContext.DrawDrawing(drawing);
			}

			var bounds = drawingVisual.ContentBounds;

			var targetBitmap = new RenderTargetBitmap(
				width * 10, height * 10, dpiX, dpiY,
				PixelFormats.Pbgra32);
			drawingVisual.Transform = new ScaleTransform(width * 10 / bounds.Width, height * 10 / bounds.Height);

			targetBitmap.Render(drawingVisual);

			// Encoding the RenderBitmapTarget as an image.
			bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap));

			byte[] values;
			using (var str = new MemoryStream()) {
				bitmapEncoder.Save(str);
				values = str.ToArray();
			}
			return Convert.ToBase64String(values);
		}
예제 #7
0
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog Filedlg = new SaveFileDialog();

            Filedlg.Filter = "PNG Images|*.png| JPEG Images |*.jpg";

            if ((bool)Filedlg.ShowDialog(this))
            {
                try
                {
                    using (FileStream savefile = new FileStream(Filedlg.FileName, FileMode.Create, FileAccess.Write))
                    {
                        Rect bounds            = VisualTreeHelper.GetDescendantBounds(paintCanvas);
                        RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, 96, 96, System.Windows.Media.PixelFormats.Default);
                        DrawingVisual      dv  = new DrawingVisual();
                        using (DrawingContext dc = dv.RenderOpen())
                        {
                            VisualBrush vb = new VisualBrush(paintCanvas);
                            dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
                        }
                        rtb.Render(dv);
                        var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
                        enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));
                        enc.Save(savefile);
                    }
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message, Title);
                }
            }
        }
        private void snapshotClicked(object sender, RoutedEventArgs e)
        {
            e.Handled = true;

            var imageSource = GridZoomControl.SnapshotToBitmapSource();

            if (imageSource == null)
            {
                MessageBox.Show("Failed to snapshot image");
                return;
            }

            var dialog = new SaveFileDialog
            {
                FileName = "Snapshot.png", Filter = "PNG File (*.png)|*.png"
            };

            if (dialog.ShowDialog(this) == true)
            {
                using (var fs = new FileStream(dialog.FileName, FileMode.Create))
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(imageSource));
                    encoder.Save(fs);
                }
            }
        }
예제 #9
0
        public static byte[] Encode(String path)
        {
            byte[] encoded;
            try
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
                bitmap.EndInit();

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));

                using (var stream = new MemoryStream())
                {
                    encoder.Save(stream);
                    encoded = stream.ToArray();
                }

                return encoded;
            }
            catch (Exception)
            {
                return null;
            }
        }
예제 #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 void onImageCapture(Affdex.Frame frame)
        {
            #region 使用一下代码测试帧捕获的图片是否可以正常生成图片,如果不能则是输入给帧的像素的数组有问题
            var    len         = frame.getBGRByteArrayLength();
            byte[] imageData   = frame.getBGRByteArray();//这里捕获的数据 不同于生成该frame时的buff 并且是3通道的数据
            int    width       = frame.getWidth();
            int    height      = frame.getHeight();
            var    ColorFormat = frame.getColorFormat();

            if (imageData != null && imageData.Length > 0)
            {
                var _stride  = (width * System.Windows.Media.PixelFormats.Rgb24.BitsPerPixel + 7) / 8;
                var imageSrc = System.Windows.Media.Imaging.BitmapSource.Create(width, height, 96d, 96d, System.Windows.Media.PixelFormats.Bgr24,
                                                                                null, imageData, _stride);

                System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(imageSrc));
                using (var stream =
                           new System.IO.FileStream(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory,
                                                                           "我是分析前图片.png"), System.IO.FileMode.Create))
                {
                    encoder.Save(stream);
                }
            }
            #endregion
        }
        /// <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);
        }
예제 #13
0
        private Color GetColorFromImage(Point p)
        {
            try
            {
                var bounds = VisualTreeHelper.GetDescendantBounds(this);
                var rtb = new RenderTargetBitmap((int) bounds.Width, (int) bounds.Height, 96, 96, PixelFormats.Default);
                rtb.Render(this);

                byte[] arr;
                var png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(rtb));
                using (var stream = new MemoryStream())
                {
                    png.Save(stream);
                    arr = stream.ToArray();
                }

                BitmapSource bitmap = BitmapFrame.Create(new MemoryStream(arr));

                var pixels = new byte[4];
                var cb = new CroppedBitmap(bitmap, new Int32Rect((int) p.X, (int) p.Y, 1, 1));
                cb.CopyPixels(pixels, 4, 0);
                return Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
            }
            catch (Exception)
            {
                return ColorBox.Color;
            }
        }
예제 #14
0
 public void AcquireClipboardContent()
 {
     try
     {
         if (Clipboard.ContainsAudio())
         {
             Audio = Clipboard.GetAudioStream();
         }
         else if (Clipboard.ContainsFileDropList())
         {
             FileDropList = Clipboard.GetFileDropList();
         }
         else if (Clipboard.ContainsImage())
         {
             using (MemoryStream ms = new MemoryStream())
             {
                 BitmapSource img = Clipboard.GetImage();
                 PngBitmapEncoder encoder = new PngBitmapEncoder();
                 encoder.Frames.Add(BitmapFrame.Create(img));
                 encoder.Save(ms);
                 ms.Seek(0, SeekOrigin.Begin);
                 Image = ms.ToArray();
             }
         }
         else if (Clipboard.ContainsText())
         {
             Text = Clipboard.GetText();
         }
         else
         {
             isEmpty = true;
         }
     }
     catch (Exception ex) { Trace.TraceError("Exception in CopyOnClipboard()", ex.StackTrace); }
 }
예제 #15
0
        /// <summary>
        /// Renders the brush.
        /// </summary>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <param name="brush">
        /// The brush.
        /// </param>
        /// <param name="w">
        /// The w.
        /// </param>
        /// <param name="h">
        /// The h.
        /// </param>
        public static void RenderBrush(string path, Brush brush, int w, int h)
        {
            var ib = brush as ImageBrush;
            if (ib != null)
            {
                var bi = ib.ImageSource as BitmapImage;
                if (bi != null)
                {
                    w = bi.PixelWidth;
                    h = bi.PixelHeight;
                }
            }

            var bmp = new RenderTargetBitmap(w, h, 96, 96, PixelFormats.Pbgra32);
            var rect = new Grid
                {
                    Background = brush,
                    Width = 1,
                    Height = 1,
                    LayoutTransform = new ScaleTransform(w, h)
                };
            rect.Arrange(new Rect(0, 0, w, h));
            bmp.Render(rect);

            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));

            using (Stream stm = File.Create(path))
            {
                encoder.Save(stm);
            }
        }
        public void Convert(IEnumerable<IAssetImageSource> sources, string target, VisualAssetInfo visualAsset)
        {
            if (sources == null)
            {
                throw new ArgumentNullException("sources");
            }
            if (string.IsNullOrEmpty(target))
            {
                throw new ArgumentNullException("target");
            }
            if (visualAsset == null)
            {
                throw new ArgumentNullException("visualAsset");
            }

            var rectangle = this.GetRectangleBounds(visualAsset.Width, visualAsset.Height, visualAsset.Margin);
            var drawingVisual = this.CreateDrawingVisual(sources, rectangle);

            var targetBitmap = new RenderTargetBitmap(visualAsset.Width, visualAsset.Height, 96, 96, PixelFormats.Pbgra32);
            targetBitmap.Render(drawingVisual);

            var png = new PngBitmapEncoder();
            png.Frames.Add(BitmapFrame.Create(targetBitmap));

            using (var stream = new FileStream(target, FileMode.Create, FileAccess.Write))
            {
                png.Save(stream);
            }
        }
예제 #17
0
파일: Program.cs 프로젝트: EFanZh/EFanZh
        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>
        /// Convert any control to a PngBitmapEncoder
        /// </summary>
        /// <param name="controlToConvert">The control to convert to an ImageSource</param>
        /// <returns>The returned ImageSource of the controlToConvert</returns>
        private static PngBitmapEncoder getImageFromControl(Control controlToConvert)
        {
            // save current canvas transform
            Transform transform = controlToConvert.LayoutTransform;

            // get size of control
            Size sizeOfControl = new Size(controlToConvert.ActualWidth, controlToConvert.ActualHeight);
            // measure and arrange the control
            controlToConvert.Measure(sizeOfControl);
            // arrange the surface
            controlToConvert.Arrange(new Rect(sizeOfControl));

            // craete and render surface and push bitmap to it
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((Int32)sizeOfControl.Width, (Int32)sizeOfControl.Height, 96d, 96d, PixelFormats.Pbgra32);
            // now render surface to bitmap
            renderBitmap.Render(controlToConvert);
            
            // encode png data
            PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
            // puch rendered bitmap into it
            pngEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));

            // return encoder
            return pngEncoder;
        }
예제 #19
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);
            }
        }
예제 #20
0
        public void Write(BitmapSource i, Stream s)
        {
            BitmapEncoder encoder = null;

            if (MimeType.Equals("image/jpeg"))
            {
                encoder = new JpegBitmapEncoder();
                ((JpegBitmapEncoder)encoder).QualityLevel = localSettings.Quality;
            }
            else if (MimeType.Equals("image/png"))
            {
                encoder = new PngBitmapEncoder();
            }
            else if (MimeType.Equals("image/gif"))
            {
                encoder = new GifBitmapEncoder();
                encoder.Palette = new BitmapPalette(i, 256);
            }

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

            using (MemoryStream outputStream = new MemoryStream())
            {
                encoder.Save(outputStream);
                outputStream.WriteTo(s);
            }
        }
예제 #21
0
 public String IconImageDataUri(S.AppWindow self)
 {
     var key = "IconImageDataUri-" + self.HWnd;
     var iconImageDataUri = System.Runtime.Caching.MemoryCache.Default.Get(key) as String; ;
     if (iconImageDataUri == null)
     {
         var iconImage = self.IconImage;
         try
         {
             using (MemoryStream memoryStream = new MemoryStream())
             {
                 BitmapEncoder encoder = new PngBitmapEncoder();
                 encoder.Frames.Add(BitmapFrame.Create(iconImage));
                 encoder.Save(memoryStream);
                 var b64String = Convert.ToBase64String(memoryStream.ToArray());
                 iconImageDataUri = "data:image/png;base64," + b64String;
                 System.Runtime.Caching.MemoryCache.Default.Add(key, iconImageDataUri, DateTimeOffset.Now.AddHours(1));
             } 
         }
         catch {
             return null;
         }
     }
     return iconImageDataUri;
 }
예제 #22
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);
        }
예제 #23
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();
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Generates an image of each page in the year book
        /// and saves it to the src folder
        /// </summary>
        /// <param name="bv"></param>
        /// <param name="folderloc"></param>
        private static void RenderPages(BookViewer bv, string folderloc)
        {
            int currentpage = bv.ViewIndex;
            //loops though each page
            foreach (Page p in bv.CurrentBook.Pages)
            {
                bv.ViewIndex = p.PageNumber;
                //forces the canvas to re-render
                BookViewer.DesignerCanvas.UpdateLayout();
                //takes a picture of the canvas
                RenderTargetBitmap rtb = new RenderTargetBitmap(PaperSize.Pixel.PaperWidth, PaperSize.Pixel.PaperHeight, 96, 96, PixelFormats.Default);
                rtb.Render(BookViewer.DesignerCanvas);
                //getting the bleed margin
                Int32Rect bleedmargin = new Int32Rect((PaperSize.Pixel.PaperWidth - PaperSize.Pixel.BleedWidth) / 2, (PaperSize.Pixel.PaperHeight - PaperSize.Pixel.BleedHeight) / 2, PaperSize.Pixel.BleedWidth, PaperSize.Pixel.BleedHeight);
                //cropping the image
                CroppedBitmap cb = new CroppedBitmap(rtb, bleedmargin);
                //encodes the image in png format
                PngBitmapEncoder pbe = new PngBitmapEncoder();
                pbe.Frames.Add(BitmapFrame.Create(cb));
                //saves the resulting image
                FileStream fs = File.Open(folderloc + "\\src\\" + (p.PageNumber+1) + ".png", FileMode.Create);
                pbe.Save(fs);
                fs.Flush();
                fs.Close();

            }
            bv.ViewIndex = currentpage;
        }
예제 #25
0
 public static void Save(BitmapSource image, string filename)
 {
     PngBitmapEncoder encoder = new PngBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(image));
     using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
         encoder.Save(stream);
 }
예제 #26
0
        private void export_Click(object sender, RoutedEventArgs e)
        {
            //Try-catch because creating the file might throw error if access is denied (run as adminstrator in that case)
            try
            {
                //Form the RenderTargetBitmap object
                double dpi = 97;           //dpi
                var    rtb = new RenderTargetBitmap(
                    (int)this.Width,       //width
                    (int)this.Height,      //height
                    dpi,                   //dpi x
                    dpi,                   //dpi y
                    PixelFormats.Pbgra32   // pixelformat
                    );
                rtb.Render(this);

                //Encoder
                var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
                enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));

                //Actually create the file and save the window screenshot there
                using (var stm = System.IO.File.Create("Arceuus library " + DateTime.UtcNow + " utc.png"))
                {
                    enc.Save(stm);
                }

                lastExported.Text = "Latest export: " + DateTime.UtcNow.ToLongTimeString() + " utc";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
예제 #27
0
		private void SaveImage(string filePath)
		{
			var encoder = new PngBitmapEncoder();
			encoder.Frames.Add(BitmapFrame.Create((BitmapSource) imageScreenshot.Source));
			using (var stream = new FileStream(filePath, FileMode.Create))
				encoder.Save(stream);
		}
예제 #28
0
        /// <summary>
        /// Exports the specified viewport.
        /// </summary>
        /// <param name="viewport">
        /// The viewport.
        /// </param>
        public void Export(Viewport3D viewport)
        {
            int m = this.OversamplingMultiplier;

            var background = this.Background;
            if (background == null)
            {
                background = Brushes.Transparent;
            }

            var bmp = Viewport3DHelper.RenderBitmap(viewport, background, m);
            BitmapEncoder encoder;
            string ext = Path.GetExtension(this.FileName);
            switch (ext.ToLower())
            {
                case ".jpg":
                    var jpg = new JpegBitmapEncoder();
                    jpg.Frames.Add(BitmapFrame.Create(bmp));
                    encoder = jpg;
                    break;
                case ".png":
                    var png = new PngBitmapEncoder();
                    png.Frames.Add(BitmapFrame.Create(bmp));
                    encoder = png;
                    break;
                default:
                    throw new InvalidOperationException("Not supported file format.");
            }

            using (Stream stm = File.Create(this.FileName))
            {
                encoder.Save(stm);
            }
        }
예제 #29
0
 public static void SaveAsPng(this BitmapSource bitmap, string filename) {
     var encoder = new PngBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(bitmap));
     using (var s = File.Create(filename)) {
         encoder.Save(s);
     }
 }
예제 #30
0
        /// <summary>
        /// Gets a PNG "screenshot" of the current UIElement
        /// </summary>
        /// <param name="source">UIElement to screenshot</param>
        /// <param name="scale">Scale to render the screenshot</param>
        /// <returns>Byte array of PNG data</returns>
        public static byte[] GetPngImage(this UIElement source, double scale = 1)
        {
            var actualHeight = source.RenderSize.Height;
            var actualWidth = source.RenderSize.Width;

            var renderHeight = actualHeight * scale;
            var renderWidth = actualWidth * scale;

            var renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
            var sourceBrush = new VisualBrush(source);

            var drawingVisual = new DrawingVisual();
            var drawingContext = drawingVisual.RenderOpen();

            using (drawingContext)
            {
                drawingContext.PushTransform(new ScaleTransform(scale, scale));
                drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Size(actualWidth, actualHeight)));
            }
            renderTarget.Render(drawingVisual);

            var pngEncoder = new PngBitmapEncoder();
            pngEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
            Byte[] imageArray;

            using (var outputStream = new MemoryStream())
            {
                pngEncoder.Save(outputStream);
                imageArray = outputStream.ToArray();
            }

            return imageArray;
        }
        public void SaveToPng( Canvas surface, string file )
        {
            // Save current canvas transform
            var transform = surface.LayoutTransform;
            // reset current transform (in case it is scaled or rotated)
            surface.LayoutTransform = null;

            var size = new Size( 1600, 900 );

            // Attentation: Measure and arrange the surface !
            surface.Measure( size );
            surface.Arrange( new Rect( size ) );

            var renderBitmap = new RenderTargetBitmap( (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32 );

            var bounds = VisualTreeHelper.GetDescendantBounds( surface );
            var dv = new DrawingVisual();
            using ( var ctx = dv.RenderOpen() )
            {
                var vb = new VisualBrush( surface );
                ctx.DrawRectangle( vb, null, new Rect( new Point(), bounds.Size ) );
            }

            renderBitmap.Render( dv );
            using ( var outStream = new FileStream( file, FileMode.OpenOrCreate, FileAccess.Write ) )
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add( BitmapFrame.Create( renderBitmap ) );
                encoder.Save( outStream );
            }

            // Restore previously saved layout
            surface.LayoutTransform = transform;
        }
        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);
        }
예제 #33
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);
            });
        }
예제 #34
0
        private void SavePatient()
        {
            // string paths = @"c:\amHealth\images";
            string filePath = @"c:\amHealth\\images\" +fname.Text+"-"+lname.Text +".jpg";
            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create((BitmapSource)imgCapture.Source));

            using (FileStream stream = new FileStream(filePath, FileMode.Create))
                encoder.Save(stream);

            _patient = App.amApp.Patients.Add();
            _patient.Lname = lname.Text;
            _patient.Fname = fname.Text;
            _patient.Gender = gender.Text;
            _patient.Dob = dob.Text;
            _patient.Height = height.Text;
            _patient.Weight = weight.Text;
            _patient.Phone = phone.Text;
            _patient.Region = region.Text;
            _patient.Sync = "F";
            _patient.Email = email.Text;
            _patient.Org = "test";
            _patient.Image = fname.Text + "-" + lname.Text + ".jpg";


            _patient.Save();
            System.Windows.MessageBox.Show("Patient saved ");
            this.DialogResult = true;

        }
예제 #35
0
        /// <summary>
        /// Handles the user clicking on the screenshot button
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void ButtonScreenshotClick(object sender, RoutedEventArgs e)
        {
            if (null == this.sensor)
            {
                this.statusBarText.Text = Properties.Resources.ConnectDeviceFirst;
                return;
            }

            // create a png bitmap encoder which knows how to save a .png file
            BitmapEncoder encoder = new PngBitmapEncoder();

            // create frame from the writable bitmap and add to encoder
            encoder.Frames.Add(BitmapFrame.Create(this.colorBitmap));

            string time = System.DateTime.Now.ToString("hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat);

            string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

            string path = Path.Combine(myPhotos, "KinectSnapshot-" + time + ".png");

            // write the new file to disk
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    encoder.Save(fs);
                }

                this.statusBarText.Text = string.Format(CultureInfo.InvariantCulture, "{0} {1}", Properties.Resources.ScreenshotWriteSuccess, path);
            }
            catch (IOException)
            {
                this.statusBarText.Text = string.Format(CultureInfo.InvariantCulture, "{0} {1}", Properties.Resources.ScreenshotWriteFailed, path);
            }
        }
예제 #36
0
    public static Cursor CreateCursor(UIElement element, int xHotSpot, 
        int yHotSpot)
    {
      element.Measure(new Size(double.PositiveInfinity, 
        double.PositiveInfinity));
      element.Arrange(new Rect(0, 0, element.DesiredSize.Width, 
        element.DesiredSize.Height));

      RenderTargetBitmap rtb = 
        new RenderTargetBitmap((int)element.DesiredSize.Width, 
          (int)element.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);
      rtb.Render(element);

      PngBitmapEncoder encoder = new PngBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(rtb));

      MemoryStream ms = new MemoryStream();
      encoder.Save(ms);

      System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);

      ms.Close();
      ms.Dispose();     

      Cursor cur = InternalCreateCursor(bmp, xHotSpot, yHotSpot);

      bmp.Dispose();

      return cur;
    }
예제 #37
0
        private static void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
        {
            var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();

            enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
            using (var stm = System.IO.File.Create(filename)) {
                enc.Save(stm);
            }
        }
예제 #38
0
        private static void SaveRTBAsPNG(RenderTargetBitmap bitmap, string filename)
        {
            var pngBitmapEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            pngBitmapEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap));

            using (var fileStream = System.IO.File.Create(filename))
                pngBitmapEncoder.Save(fileStream);
        }
        private void SavePicturetoFile(ImageSource symbolPicture, string outputDir, string fname)
        {
            FileStream fs      = new FileStream(System.IO.Path.Combine(outputDir, fname), FileMode.Create);
            var        encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(symbolPicture as System.Windows.Media.Imaging.BitmapSource));
            encoder.Save(fs);
            fs.Flush();
        }
        public Byte[] ImageToByte(BitmapSource source)
        {
            var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            var frame   = System.Windows.Media.Imaging.BitmapFrame.Create(source);

            encoder.Frames.Add(frame);
            var stream = new MemoryStream();

            encoder.Save(stream);
            return(stream.ToArray());
        }
예제 #41
0
        public System.Drawing.Bitmap BitmapImageToBitMap(BitmapImage bitmapImage)
        {
            var ms      = new MemoryStream();
            var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
            encoder.Save(ms);
            var bmp = new System.Drawing.Bitmap(ms);

            return(bmp);
        }
예제 #42
0
        /// <summary>
        /// 保存System.Windows.Controls.Image
        /// </summary>
        /// <param name="myImage"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public void saveImage(System.Windows.Controls.Image myImage, string savePath)
        {
            System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
            bitmapImage = ((System.Windows.Media.Imaging.BitmapImage)myImage.Source);
            System.Windows.Media.Imaging.PngBitmapEncoder pngBitmapEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            System.IO.FileStream stream = new System.IO.FileStream(savePath, FileMode.Create);

            pngBitmapEncoder.Interlace = PngInterlaceOption.On;
            pngBitmapEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapImage));
            pngBitmapEncoder.Save(stream);
            stream.Flush();
            stream.Close();
        }
예제 #43
0
        public static Sd.Bitmap ToBitmap(this Si.BitmapSource input)
        {
            Sd.Bitmap output = new Sd.Bitmap(10, 10);
            using (MemoryStream outStream = new MemoryStream())
            {
                Si.PngBitmapEncoder enc = new Si.PngBitmapEncoder();

                enc.Frames.Add(Si.BitmapFrame.Create(input));
                enc.Save(outStream);
                output = new Sd.Bitmap(outStream);
            }

            return(output);
        }
예제 #44
0
파일: Helper.cs 프로젝트: radtek/videomaker
        public static System.Drawing.Bitmap ConvertWindowToBitmap(Window window, int dpi)
        {
            var rtb = new RenderTargetBitmap(
                (int)window.Width,   //width
                (int)window.Width,   //height
                dpi,                 //dpi x
                dpi,                 //dpi y
                PixelFormats.Pbgra32 // pixelformat
                );

            rtb.Render(window);
            var         enc   = new System.Windows.Media.Imaging.PngBitmapEncoder();
            BitmapFrame frame = System.Windows.Media.Imaging.BitmapFrame.Create(rtb);

            return(null);
        }
예제 #45
0
        public static Bitmap ImageSourceABitmap(ImageSource imagen)
        {
            if (imagen == null)
            {
                return(null);
            }

            MemoryStream ms      = new MemoryStream();
            var          encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

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

            return((Bitmap)Bitmap.FromStream(ms));
        }
예제 #46
0
        private static void BSkyGraphicControlToImageFile(BSkyGraphicControl bsgc, string fullpathimgfilename)
        {
            System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
            myImage.Source = bsgc.BSkyImageSource;

            System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
            bitmapImage = ((System.Windows.Media.Imaging.BitmapImage)myImage.Source);
            System.Windows.Media.Imaging.PngBitmapEncoder pngBitmapEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            System.IO.FileStream stream = new System.IO.FileStream(fullpathimgfilename, FileMode.Create);

            pngBitmapEncoder.Interlace = PngInterlaceOption.On;
            pngBitmapEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapImage));
            pngBitmapEncoder.Save(stream);
            stream.Flush();
            stream.Close();
        }
예제 #47
0
        void salvaCanvasSuFile(Canvas canvas, string nomeFile)
        {
            BitmapSource bmpSource = (BitmapSource)imgMaschera.Source;

            Int32 newWidth  = bmpSource.PixelWidth;
            Int32 newHeight = bmpSource.PixelHeight;

            RenderTargetBitmap rtb = new RenderTargetBitmap(newWidth, newHeight, bmpSource.DpiX, bmpSource.DpiY, PixelFormats.Pbgra32);

            rtb.Render(canvas);
            var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();

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

            using (var stm = System.IO.File.Create(nomeFile)) {
                enc.Save(stm);
            }
        }
        private ImageSource SavePicturetoFile4(CIMSymbol cimSymbol, string fname)
        {
            var si1 = new SymbolStyleItem()
            {
                Symbol      = cimSymbol,
                PatchHeight = 32,
                PatchWidth  = 32
            };
            ImageSource _symbolPicture = si1.PreviewImage;

            Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fname));
            FileStream fs      = new FileStream(fname, FileMode.Create);
            var        encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(_symbolPicture as System.Windows.Media.Imaging.BitmapSource));
            encoder.Save(fs);
            fs.Flush();
            return(_symbolPicture);
        }
        static byte[] GetBytesFromBitmapSource(System.Windows.Media.Imaging.BitmapSource bmp)
        {
            if (bmp == null)
            {
                return(null);
            }

            System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            //encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            // byte[] bit = new byte[0];
            using (MemoryStream stream = new MemoryStream())
            {
                encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
                encoder.Save(stream);
                byte[] bit = stream.ToArray();
                stream.Close();

                return(bit);
            }
        }
예제 #50
0
        private void button2_Click(object sender, EventArgs e)
        {
            string FileName = "D://FileName.gif";
            var    enc      = new System.Windows.Media.Imaging.PngBitmapEncoder();

            string [] FileNames = richTextBox1.Text.Split(',');

            System.Windows.Media.Imaging.GifBitmapEncoder gEnc = new GifBitmapEncoder();

            foreach (var x in FileNames)
            {
                System.Drawing.Bitmap bmpImage = new Bitmap(x);
                var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmpImage.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
                gEnc.Frames.Add(BitmapFrame.Create(src));
            }
            gEnc.Save(new FileStream(FileName, FileMode.Create));



            //    string FileName = "D://FileName.gif";
            //    var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
            //    string []FileNames=richTextBox1.Text.Split(',');
            //    foreach (var x in FileNames)
            //    {
            //      //  var jpgFile = File.OpenRead(x);
            //         var uriBitmap = BitmapDecoder.Create(new Uri(x,UriKind.Absolute) ,BitmapCreateOptions.None,BitmapCacheOption.Default);

            //            foreach (var frame in uriBitmap.Frames)
            //            {
            //                enc.Frames.Add(frame);
            //            }
            // }
            //    using (var stm = System.IO.File.Create(FileName))
            //    {
            //        enc.Save(stm);
            //    }
        }
예제 #51
0
        public static void SaveGray16(string path, int width, int height, UInt16[] data)
        {
            int stride = width * 2; // ピクセル当たり2Byte

            // Creates a new empty image with the pre-defined palette
            System.Windows.Media.Imaging.BitmapSource image = System.Windows.Media.Imaging.BitmapSource.Create(
                width,
                height,
                96,
                96,
                System.Windows.Media.PixelFormats.Gray16,
                null,
                data,
                stride);
            System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Create);
            System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image));
            encoder.Save(stream);

            stream.Close();
        }
예제 #52
0
        /// <summary>Saves the current rendered image to the directory of the executable, with a random filename.</summary>
        public void SaveImageToRandomFile()
        {
            var image = ImageProvider.Image as BitmapSource;

            if (image == null)
            {
                return;
            }

            var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            var frame   = BitmapFrame.Create(image);

            encoder.Frames.Add(frame);

            var fileName = System.IO.Path.GetRandomFileName() + ".png";

            System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
            using (var file = System.IO.File.Create(fileName))
            {
                encoder.Save(file);
            }
        }
예제 #53
0
        public static Bitmap ImageSourceABitmap(ImageSource imagen, ImageFormat formato)
        {
            if (imagen == null)
            {
                return(null);
            }

            MemoryStream ms      = new MemoryStream();
            var          encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

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

            Bitmap imagenConvertida = (Bitmap)System.Drawing.Image.FromStream(ms);

            MemoryStream ms2 = new MemoryStream();

            imagenConvertida.Save(ms2, formato);

            return((Bitmap)Bitmap.FromStream(ms));
        }
예제 #54
0
        public static bool SaveImage(string filePath, string userName, Canvas canvas, Window window)
        {
            string path = $"{filePath}\\{userName}-CanvasImage";

            while (File.Exists(path))
            {
                path = $"{filePath}\\{userName}-CanvasImage{imageCount++}";
            }

            Size size = new Size(window.Width, window.Height);

            canvas.Measure(size);
            //uscBasicDrawing.cnvDrawArea.Arrange(new Rect(size));

            const int dpi = 96;

            var rtb = new RenderTargetBitmap(
                (int)canvas.ActualWidth,
                (int)canvas.ActualHeight,
                dpi,                 //dpi x
                dpi,                 //dpi y
                PixelFormats.Pbgra32 // pixelformat
                );

            rtb.Render(canvas);

            var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();

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

            using (var fileStream = File.Create(path))
            {
                enc.Save(fileStream);
            }

            return(true);
        }
        public static int SaveWindowPicByHandle(Window win, IntPtr hWnd, String path)
        {
            log.InfoFormat("Save snap window picture to path:{0}", path);
            string dir = Path.GetDirectoryName(path);

            if (!Directory.Exists(dir))
            {
                log.Info("The snap window picture for the specified path is not existed.");
            }
            if (File.Exists(path))
            {
                log.Info("The snap window picture for the file is existed.");
            }
            IntPtr  hscrdc  = GetWindowDC(hWnd);
            Control control = Control.FromChildHandle(hWnd);
            IntPtr  hbitmap;

            if (control != null)
            {
                hbitmap = CreateCompatibleBitmap(hscrdc, control.Width, control.Height);
            }
            else
            {
                uint primaryDpiX = 96;
                uint primaryDpiY = 96;
                try
                {
                    DpiUtil.GetDpiByScreen(Screen.PrimaryScreen, out primaryDpiX, out primaryDpiY);
                }
                catch (Exception e)
                {
                }

                hbitmap = CreateCompatibleBitmap(hscrdc, Convert.ToInt32(win.ActualWidth * primaryDpiX / 96), Convert.ToInt32(win.ActualHeight * primaryDpiY / 96));
            }

            IntPtr hmemdc = CreateCompatibleDC(hscrdc);

            SelectObject(hmemdc, hbitmap);

            UInt32 systemFlag = 0;

            if (System.Environment.OSVersion.Version.Major > 6 || (System.Environment.OSVersion.Version.Major == 6 && System.Environment.OSVersion.Version.Minor > 1))
            {
                systemFlag = 2;
            }

            log.InfoFormat("OS Version, major:{0}, minor:{1}, system flag:{2}", System.Environment.OSVersion.Version.Major, System.Environment.OSVersion.Version.Minor, systemFlag);
            bool re = PrintWindow(hWnd, hmemdc, systemFlag);

            if (re)
            {
                //using(Bitmap bmp = Bitmap.FromHbitmap(hbitmap))
                //{
                //    DeleteObject(hbitmap);
                //    DeleteDC(hmemdc);
                //    ReleaseDC(hWnd, hscrdc);
                //    bmp.Save(path, ImageFormat.Png);
                //}

                BitmapSource nImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    hbitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                log.InfoFormat("Snapped image, PixelWidth:{0}, PixelHeight:{1}, Width:{2}, Height:{3}", nImage.PixelWidth, nImage.PixelHeight, nImage.Width, nImage.Height);
                System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(nImage));
                try
                {
                    using (FileStream stream = new FileStream(path, FileMode.Create))
                    {
                        encoder.Save(stream);
                    }
                }
                catch (FileNotFoundException e)
                {
                    log.InfoFormat("Failed to save screen picture, exception:{0}", e);
                    return(-2);
                }
                finally
                {
                    log.Info("Save picture successfully and release resource.");
                    DeleteObject(hbitmap);
                    DeleteDC(hmemdc);
                    ReleaseDC(hWnd, hscrdc);
                }
            }
            else
            {
                log.Info("Failed to print window by handle");
                DeleteObject(hbitmap);
                DeleteDC(hmemdc);
                ReleaseDC(hWnd, hscrdc);
                return(-1);
            }
            return(0);
        }
예제 #56
0
        /// <summary>
        /// Permite guardar el canvas o la gráfica como una imagen ".png".
        /// <para>Base: http://tutorialgenius.blogspot.com/2014/12/saving-window-or-canvas-as-png-bitmap.html</para>
        /// </summary>
        private void GuardarImagen_Click(object sender, RoutedEventArgs e)
        {
            Visual pantalla = miCanvas;

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName   = "Grafica";               // Default file name
            dlg.DefaultExt = ".png";                  // Default file extension
            dlg.Filter     = "PNG File (.png)|*.png"; // Filter files by extension

            // Show save file dialog box
            Nullable <bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                string filename = dlg.FileName;

                if (miCanvas.Visibility == Visibility.Visible)
                {
                    Size size = new Size(this.Width, this.Height);
                    miCanvas.Measure(size);
                }
                else if (GBarras.Visibility == Visibility.Visible)
                {
                    pantalla = GBarras;
                }
                else if (GArea.Visibility == Visibility.Visible)
                {
                    pantalla = GArea;
                }
                else if (GBurbuja.Visibility == Visibility.Visible)
                {
                    pantalla = GBurbuja;
                }
                else if (GColumna.Visibility == Visibility.Visible)
                {
                    pantalla = miCanvas;
                }
                else if (GLinea.Visibility == Visibility.Visible)
                {
                    pantalla = GLinea;
                }
                else if (GTarta.Visibility == Visibility.Visible)
                {
                    pantalla = GTarta;
                }
                else if (GDispersion.Visibility == Visibility.Visible)
                {
                    pantalla = GDispersion;
                }

                var rtb = new RenderTargetBitmap(
                    (int)this.Width,     //width
                    (int)this.Height,    //height
                    96,                  //dpi x
                    96,                  //dpi y
                    PixelFormats.Pbgra32 // pixelformat
                    );
                rtb.Render(pantalla);

                var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
                enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));

                using (var stm = System.IO.File.Create(filename))
                    enc.Save(stm);
            }
        }
예제 #57
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);
        }
예제 #58
0
    // since inheritance of Window does not work, the eventhandler have to be static methods and added after generation of the Window object

    // keyboard is pressed
    private static void InkCanvas_KeyDown(object sender, KeyEventArgs e)
    {
        Key Taste = e.Key;
        // the sender object is the object that generated the event
        InkCanvas objInkCanvas = (InkCanvas)sender;

        if (Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftCtrl))
// the following line only works with .Net 4.x
//		if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
        {         // if Ctrl is pressed
            switch (Taste)
            {
            case Key.C:                     // copy marked area
                objInkCanvas.CopySelection();
                break;

            case Key.O:                     // open ink drawing
                Microsoft.Win32.OpenFileDialog objOpenDialog = new Microsoft.Win32.OpenFileDialog();
                objOpenDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objOpenDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objOpenDialog.FileName, FileMode.Open);
                    objInkCanvas.Strokes.Add(new StrokeCollection(objFileStream));
                    objFileStream.Dispose();
                }
                break;

            case Key.P:                     // save grafic as PNG file
                Microsoft.Win32.SaveFileDialog objPNGDialog = new Microsoft.Win32.SaveFileDialog();
                objPNGDialog.Filter = "png files (*.png)|*.png";
                if ((bool)objPNGDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objPNGDialog.FileName, FileMode.Create);
                    System.Windows.Media.Imaging.RenderTargetBitmap objRenderBitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)objInkCanvas.ActualWidth, (int)objInkCanvas.ActualHeight, 96.0, 96.0, System.Windows.Media.PixelFormats.Default);
                    objRenderBitmap.Render(objInkCanvas);
                    System.Windows.Media.Imaging.BitmapFrame      objBitmapFrame = System.Windows.Media.Imaging.BitmapFrame.Create(objRenderBitmap);
                    System.Windows.Media.Imaging.PngBitmapEncoder objImgEncoder  = new System.Windows.Media.Imaging.PngBitmapEncoder();
// alternative for JPG:								System.Windows.Media.Imaging.JpegBitmapEncoder objImgEncoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
                    objImgEncoder.Frames.Add(objBitmapFrame);
                    objImgEncoder.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.S:                             // save ink drawing
                Microsoft.Win32.SaveFileDialog objSaveDialog = new Microsoft.Win32.SaveFileDialog();
                objSaveDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objSaveDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objSaveDialog.FileName, FileMode.Create);
                    objInkCanvas.Strokes.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.V:                     // paste marked area
                objInkCanvas.Paste();
                break;

            case Key.X:                     // cut marked area
                objInkCanvas.CutSelection();
                break;
            }
        }
        else
        {         // no Ctrl key is pressed
            if (Keyboard.Modifiers == ModifierKeys.None)
            {     // only when no other modifier keys are pressed
                switch (Taste)
                {
                case Key.B:                         // next background color
                    Brush ActualBackColor = (Brush)BrushQueue.Dequeue();
                    BrushQueue.Enqueue(ActualBackColor);
                    objInkCanvas.Background = ActualBackColor;
                    break;

                case Key.C:                         // clear window content
                    objInkCanvas.Strokes.Clear();
                    break;

                case Key.D:                         // switch to draw mode
                    if (objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreHighLightSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreHighLightSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreHighLightColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Ellipse;
                        objInkCanvas.DefaultDrawingAttributes.IsHighlighter = false;
                        objInkCanvas.DefaultDrawingAttributes.Color         = StoreInkColor;
                        objInkCanvas.DefaultDrawingAttributes.Height        = StoreInkSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width         = StoreInkSizeWidth;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    break;

                case Key.E:                         // // switch to erase mode (and toggle it)
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByStroke:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;

                    case InkCanvasEditingMode.EraseByPoint:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
                        break;

                    case InkCanvasEditingMode.Ink:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;
                    }
                    break;

                case Key.H:                         // switch to highlight mode
                    if (!objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreInkSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreInkSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreInkColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.Color = StoreHighLightColor;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    objInkCanvas.DefaultDrawingAttributes.IsHighlighter = true;
                    objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Rectangle;
                    if (StoreHighLightSizeWidth > 0.0)
                    {
                        objInkCanvas.DefaultDrawingAttributes.Height = StoreHighLightSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width  = StoreHighLightSizeWidth;
                    }
                    break;

                case Key.N:                         // next foreground color
                    Color ActualFrontColor = (Color)ColorQueue.Dequeue();
                    ColorQueue.Enqueue(ActualFrontColor);
                    objInkCanvas.DefaultDrawingAttributes.Color = ActualFrontColor;
                    break;

                case Key.Q:                         // close window
                    // event is handled now
                    e.Handled = true;
                    // parent object is Window
                    ((Window)(objInkCanvas).Parent).Close();
                    break;

                case Key.S:                         // start marking
                    objInkCanvas.Select(new System.Windows.Ink.StrokeCollection());
                    break;

                case Key.OemMinus:                         // shrink brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width > 3.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width - 2.0, objInkCanvas.EraserShape.Height - 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height > 3.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height - 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width - 2.0;
                        }
                        break;
                    }
                    break;

                case Key.OemPlus:                         // enlarge brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width < 50.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width + 2.0, objInkCanvas.EraserShape.Height + 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height < 50.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height + 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width + 2.0;
                        }
                        break;
                    }
                    break;
                }
            }
        }
    }
예제 #59
0
        private void btnABC_Click(object sender, RoutedEventArgs e)
        {
            abcFile abc;

            string abcname = "";

            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.RestoreDirectory = true;
            ofd.Title            = "Open ABC File";
            ofd.Filter           = "FontMaker ABC File (*.abc)|*.abc";
            if ((bool)ofd.ShowDialog())
            {
                FileStream      fs = new FileStream(ofd.FileName, FileMode.Open);
                BigEndianReader br = new BigEndianReader(fs);

                br.BaseStream.Position = 0;

                abc = new abcFile();

                abc.Read(br);

                br.Close();
                fs.Close();

                abcname = ofd.SafeFileName;
            }
            else
            {
                return;
            }

            if (abc.Height < 0 || abc.Height > 64)
            {
                WriteLog("ABC import failed: Height " + abc.Height + " out of range (0-64).");
                return;
            }
            if (abc.TopPadding < 0 || abc.TopPadding > 64)
            {
                WriteLog("ABC import failed: Top padding " + abc.TopPadding + " out of range (0-64).");
                return;
            }
            if (abc.BottomPadding < 0 || abc.BottomPadding > 64)
            {
                WriteLog("ABC import failed: Bottom padding " + abc.BottomPadding + " out of range (0-64).");
                return;
            }
            if (abc.YAdvance < 0 || abc.YAdvance > 64)
            {
                WriteLog("ABC import failed: Indent " + abc.YAdvance + " out of range (0-64).");
                return;
            }

            ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.RestoreDirectory = true;
            ofd.Title            = "Open Font Sheet";
            ofd.Filter           = "Converted FontMaker Image (*.png)|*.png";
            if ((bool)ofd.ShowDialog())
            {
                System.Drawing.Image sheet = System.Drawing.Image.FromFile(ofd.FileName);

                for (int i = 0; i < abc.GlyphCount; i++)
                {
                    System.Drawing.Rectangle rect = new System.Drawing.Rectangle(abc.GlyphTable[i].Left,
                                                                                 abc.GlyphTable[i].Top,
                                                                                 (abc.GlyphTable[i].Right - abc.GlyphTable[i].Left),
                                                                                 (abc.GlyphTable[i].Bottom - abc.GlyphTable[i].Top));

                    if (rect.Left + rect.Width > sheet.Width)
                    {
                        rect.Width = sheet.Width - rect.Left;
                    }

                    if (rect.Top + rect.Height > sheet.Height)
                    {
                        rect.Height = sheet.Height - rect.Top;
                    }

                    //today i learned about empty characters
                    if (rect.Width == 0)
                    {
                        rect.Width = 1;
                    }
                    if (rect.Height == 0)
                    {
                        rect.Height = 1;
                    }

                    Bitmap bm = new Bitmap(sheet);
                    System.Drawing.Imaging.BitmapData bd = bm.LockBits(rect,
                                                                       System.Drawing.Imaging.ImageLockMode.WriteOnly,
                                                                       bm.PixelFormat);

                    var sauce = BitmapSource.Create(bd.Width, bd.Height, 96, 96, System.Windows.Media.PixelFormats.Bgra32, null, bd.Scan0, bd.Stride * bd.Height, bd.Stride);

                    MemoryStream ms      = new MemoryStream();
                    var          encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(sauce));
                    encoder.Save(ms);
                    ms.Flush();

                    var dispwidth = abc.GlyphTable[i].Width;

                    if (abc.CharCodes[i] == 0x20)
                    {
                        var periodindex = package.Fonts[fontslist.SelectedIndex].FindCharacter(0x2C);

                        if (periodindex != -1)
                        {
                            dispwidth = package.Fonts[fontslist.SelectedIndex].Characters[periodindex].Data.dispWidth;
                        }
                        else
                        {
                            dispwidth = 4;
                        }
                    }


                    package.AddCustomCharacter(abc.CharCodes[i], fontslist.SelectedIndex, System.Drawing.Image.FromStream(ms), CharTint.None, true, dispwidth);

                    ms.Close();
                    bm.Dispose();
                }

                //for (int i = 0; i < package.Fonts[fontslist.SelectedIndex].Characters.Count; i++)
                //{
                //	package.Fonts[fontslist.SelectedIndex].Characters[i].Data.dispHeight = (ushort)abc.YAdvance;
                //}
                //
                //UpdateFontInfo((short)abc.Height, (short)abc.TopPadding, (short)abc.BottomPadding, 0);
                UpdateFontDisplay();

                WriteLog("Characters successfully imported from abc file \"" + abcname + "\".");
            }
        }