Exemplo n.º 1
0
            private (System.IO.Stream, string fileExtension) StreamFromBitmapSource(System.Windows.Media.Imaging.BitmapSource bmpSource)
            {
                var pngStream  = new System.IO.MemoryStream();
                var pngEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                var pngFrame   = System.Windows.Media.Imaging.BitmapFrame.Create(bmpSource);

                pngEncoder.Frames.Add(pngFrame);
                pngEncoder.Save(pngStream);
                pngStream.Seek(0, System.IO.SeekOrigin.Begin);

                var jpgStream  = new System.IO.MemoryStream();
                var jpgEncoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
                var jpgFrame   = System.Windows.Media.Imaging.BitmapFrame.Create(bmpSource);

                jpgEncoder.Frames.Add(jpgFrame);
                jpgEncoder.Save(jpgStream);
                jpgStream.Seek(0, System.IO.SeekOrigin.Begin);

                var stream    = pngStream.Length < jpgStream.Length ? pngStream : jpgStream;
                var strExt    = pngStream.Length < jpgStream.Length ? ".png" : ".jpg";
                var altStream = pngStream.Length < jpgStream.Length ? jpgStream : pngStream;

                altStream.Dispose();

                return(stream, strExt);
            }
Exemplo n.º 2
0
        void SaveImage()
        {
            Rect rect = new Rect(rectangleCopy.Margin.Left, rectangleCopy.Margin.Top, rectangleCopy.Width, rectangleCopy.Height);

            System.Drawing.Bitmap bit     = CopyHelper.CutPicture(rect);
            ImageSource           ISource = CopyHelper.BitMapToImageSource(bit);

            Clipboard.SetImage(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bit.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()));

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter           = "JPEG Files(*.jpg)|*.jpg|PNG Files (*.png)|*.png";
            sfd.RestoreDirectory = true;//保存对话框是否记忆上次打开的目录
            if (sfd.ShowDialog() == true)
            {
                var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)ISource));
                using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
                    encoder.Save(stream);

                this.Close();
                if (winMain != null)
                {
                    winMain.Show();
                }
            }
        }
        private static void WritePNG(RENDERTARGET rt, System.IO.Stream writer)
        {
            // Save the image to a location on the disk.
            var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rt));
            encoder.Save(writer);
        }
Exemplo n.º 4
0
        public void WritePNG(System.IO.Stream writer)
        {
            // Save the image to a location on the disk.
            var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(_RenderTarget));
            encoder.Save(writer);
        }
Exemplo n.º 5
0
        public static System.Drawing.Bitmap ToBitmap(this ImageSource imageSource)
        {
            MemoryStream ms      = new MemoryStream();
            var          encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(imageSource as System.Windows.Media.Imaging.BitmapSource));
            encoder.Save(ms);
            return(new System.Drawing.Bitmap(ms));
        }
Exemplo n.º 6
0
 public static void SaveToImage(System.Windows.FrameworkElement ui, string fileName, double scale = 1)
 {
     System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
     System.Windows.Media.Imaging.RenderTargetBitmap bmp = new System.Windows.Media.Imaging.RenderTargetBitmap((int)(scale * ui.ActualWidth), (int)(scale * ui.ActualHeight), scale * 96, scale * 96, System.Windows.Media.PixelFormats.Pbgra32);
     bmp.Render(ui);
     System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
     encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
     encoder.Save(fs);
     fs.Close();
 }
Exemplo n.º 7
0
        //Method for rewriting a BitmapSource to a writable stream for a text file
        public static byte[] BitmapSourceToByte(System.Windows.Media.Imaging.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());
        }
Exemplo n.º 8
0
        public void DrawStringTest()
        {
            const int    ColumnCount  = 10;
            const int    MaxDrawCount = 30; // use int.MaxValue to draw them all
            const double fontSize     = 50d;
            // the height of each cell has to include over/under hanging glyphs
            var cellSize = new Size(fontSize, fontSize * _glyphTypeface.Height);

            var glyphs = from glyphIndex in _glyphTypeface.CharacterToGlyphMap.Values select _glyphTypeface.GetGlyphOutline(glyphIndex, fontSize, 1d);

            // now create the visual we'll draw them to
            var dv        = new System.Windows.Media.DrawingVisual();
            var drawCount = -1;

            using (var dc = dv.RenderOpen())
            {
                foreach (var g in glyphs)
                {
                    drawCount++;
                    if (drawCount >= MaxDrawCount)
                    {
                        break;                            // don't draw more than you want
                    }
                    if (g.IsEmpty())
                    {
                        continue;              // don't draw the blank ones
                    }
                    // center horizontally in the cell
                    var xOffset = (drawCount % ColumnCount) * cellSize.Width + (cellSize.Width - g.Bounds.Width) / 2d;
                    // place the character on the baseline of the cell
                    var yOffset = (drawCount / ColumnCount) * cellSize.Height + fontSize * _glyphTypeface.Baseline;
                    dc.PushTransform(new System.Windows.Media.TranslateTransform(xOffset, yOffset));
                    dc.DrawGeometry(System.Windows.Media.Brushes.Red, null, g);
                    dc.Pop(); // get rid of the transform
                }
            }

            var rowCount = drawCount / ColumnCount;

            if (drawCount % ColumnCount != 0)
            {
                rowCount++;                               // to include partial rows
            }
            var bitWidth  = (int)Math.Ceiling(cellSize.Width * ColumnCount);
            var bitHeight = (int)Math.Ceiling(cellSize.Height * rowCount);
            var bmp       = new System.Windows.Media.Imaging.RenderTargetBitmap(bitWidth, bitHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);

            bmp.Render(dv);

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

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
            using (var file = new FileStream("FontTable.png", FileMode.Create)) encoder.Save(file);
        }
Exemplo n.º 9
0
    static void convert(double dpi, string path, string out_path)
    {
        double scale = dpi / 96.0;

        System.Windows.Xps.Packaging.XpsDocument xpsDoc =
            new System.Windows.Xps.Packaging.XpsDocument(
                path, System.IO.FileAccess.Read);
        if (xpsDoc == null)
        {
            throw new System.Exception("XpsDocumentfailed");
        }
        System.Windows.Documents.FixedDocumentSequence docSeq =
            xpsDoc.GetFixedDocumentSequence();
        if (docSeq == null)
        {
            throw new System.Exception("GetFixedDocumentSequence failed");
        }
        System.Windows.Documents.DocumentReferenceCollection drc = docSeq.References;
        int index = 0;

        foreach (System.Windows.Documents.DocumentReference dr in drc)
        {
            System.Windows.Documents.FixedDocument dp = dr.GetDocument(false);
            foreach (System.Windows.Documents.PageContent pc in dp.Pages)
            {
                System.Windows.Documents.FixedPage fixedPage = pc.GetPageRoot(false);
                double width           = fixedPage.Width;
                double height          = fixedPage.Height;
                System.Windows.Size sz = new System.Windows.Size(width, height);
                fixedPage.Measure(sz);
                fixedPage.Arrange(
                    new System.Windows.Rect(new System.Windows.Point(), sz));
                fixedPage.UpdateLayout();
                System.Windows.Media.Imaging.BitmapImage bitmap =
                    new System.Windows.Media.Imaging.BitmapImage();
                System.Windows.Media.Imaging.RenderTargetBitmap renderTarget =
                    new System.Windows.Media.Imaging.RenderTargetBitmap(
                        ceil(scale * width), ceil(scale * height), dpi, dpi,
                        System.Windows.Media.PixelFormats.Default);
                renderTarget.Render(fixedPage);
                System.Windows.Media.Imaging.BitmapEncoder encoder =
                    new System.Windows.Media.Imaging.PngBitmapEncoder();
                encoder.Frames.Add(
                    System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget));
                string filename = string.Format("{0}_{1}.png", out_path, index);
                System.IO.FileStream pageOutStream = new System.IO.FileStream(
                    filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                encoder.Save(pageOutStream);
                pageOutStream.Close();
                System.Console.WriteLine(filename);
                ++index;
            }
        }
    }
Exemplo n.º 10
0
        public static Bitmap ToBitmap(this Media.Imaging.BitmapSource source)
        {
            Bitmap bitmap;

            using (MemoryStream outStream = new MemoryStream())
            {
                var enc = new Media.Imaging.PngBitmapEncoder();
                enc.Frames.Add(Media.Imaging.BitmapFrame.Create(source));
                enc.Save(outStream);
                bitmap = new Bitmap(outStream);
            }
            return(bitmap);
        }
        void SaveAsPng(string exportFilename, System.Windows.Media.Imaging.BitmapSource exportImage)
        {
            if (exportFilename == string.Empty)
                return;

            using (System.IO.FileStream stream = new System.IO.FileStream(exportFilename, 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(exportImage));
                encoder.Save(stream);
                stream.Close();
            }
        }
Exemplo n.º 12
0
        public System.Drawing.Image ImageWpfToGdi2(ImageSource image)
        {
            var ms      = new System.IO.MemoryStream();
            var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(
                                   (System.Windo‌​ws.Media.Imaging.Bit‌​mapSource)image));
            encoder.Save(ms);
            ms.Flush();
            var btm = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms);

            return(btm);
        }
Exemplo n.º 13
0
        public System.Drawing.Bitmap RenderSingleCharacter(ushort glyphIndex, System.Drawing.Color backColor, System.Drawing.Color foreColor, int fontSize)
        {
            try
            {
                var geometry      = _glyphTypeface.GetGlyphOutline(glyphIndex, fontSize, 1);
                var advanceWidth  = _glyphTypeface.AdvanceWidths[glyphIndex];
                var cellSize      = new Size(fontSize, fontSize * _glyphTypeface.Height);
                var offsetX       = advanceWidth * cellSize.Width;
                var offsetY       = fontSize * _glyphTypeface.Baseline;
                var drawingVisual = new System.Windows.Media.DrawingVisual();
                var brush         = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(foreColor.A, foreColor.R, foreColor.G, foreColor.B));
                var pen           = new System.Windows.Media.Pen();
                using (var dc = drawingVisual.RenderOpen())
                {
                    dc.PushTransform(new System.Windows.Media.TranslateTransform(0, offsetY));
                    dc.DrawGeometry(brush, null, geometry);
                    dc.Pop(); // get rid of the transform
                }

                var bitWidth    = (int)Math.Ceiling(offsetX);
                var bitHeight   = (int)Math.Ceiling(cellSize.Height);
                var targetImage = new System.Windows.Media.Imaging.RenderTargetBitmap(bitWidth, bitHeight, Dpi, Dpi, System.Windows.Media.PixelFormats.Pbgra32);
                targetImage.Render(drawingVisual);

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

                var bmp = new System.Drawing.Bitmap(bitWidth, bitHeight);
                bmp.SetResolution(Dpi, Dpi);
                using (var graphics = System.Drawing.Graphics.FromImage(bmp))
                {
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphics.Clear(backColor);

                    using (var ms = new MemoryStream())
                    {
                        bmpEncoder.Save(ms);
                        graphics.DrawImage(System.Drawing.Image.FromStream(ms), new System.Drawing.PointF(0, 0));
                    }

                    graphics.Save();
                }

                return(bmp);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
Exemplo n.º 14
0
        static public void Save16BitGrayPng(string filePath, ushort[] pixels, int width, int height)
        {
            var g16 = new System.Windows.Media.Imaging.WriteableBitmap(width, height, 96.0, 96.0,
                                                                       System.Windows.Media.PixelFormats.Gray16, null);

            g16.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), pixels, width * 2, 0);

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

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(g16));
            using (var stream = System.IO.File.OpenWrite(filePath)) {
                encoder.Save(stream);
            }
        }
Exemplo n.º 15
0
        System.Drawing.Image ImageSourceConvertToGDI()
        {
            Rect        rect    = new Rect(rectangleCopy.Margin.Left, rectangleCopy.Margin.Top, rectangleCopy.Width, rectangleCopy.Height);
            ImageSource ISource = CopyHelper.BitMapToImageSource(CopyHelper.CutPicture(rect));
            var         encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)ISource));

            MemoryStream ms = new MemoryStream();

            encoder.Save(ms);
            ms.Flush();
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            return(img);
        }
        private void saveProjectImg(string ProjectPath)
        {
            var imagePath = Path.Combine(Path.GetDirectoryName(ProjectPath), Path.GetFileNameWithoutExtension(ProjectPath));
            var _pwvm     = ServiceLocator.Default.ResolveType <ProjectWizardViewModel>();
            var src       = (System.Windows.Media.Imaging.BitmapSource)_pwvm?.ProfileImageBrush?.ImageSource;

            if (src != null)
            {
                using var fs1 = new FileStream(Path.Combine(imagePath, "img.png"), FileMode.OpenOrCreate);
                var frame = System.Windows.Media.Imaging.BitmapFrame.Create(src);
                var enc   = new System.Windows.Media.Imaging.PngBitmapEncoder();
                enc.Frames.Add(frame);
                enc.Save(fs1);
            }
        }
        static byte[] GetBytesFromBitmapSource(System.Windows.Media.Imaging.BitmapSource bmp)
        {
            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);
            }
        }
        void SaveAsPng(string exportFilename, System.Windows.Media.Imaging.BitmapSource exportImage)
        {
            if (exportFilename == string.Empty)
            {
                return;
            }

            using (System.IO.FileStream stream = new System.IO.FileStream(exportFilename, 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(exportImage));
                encoder.Save(stream);
                stream.Close();
            }
        }
Exemplo n.º 19
0
 static void convert(double dpi, string path, string out_path)
 {
     double scale = dpi / 96.0;
     System.Windows.Xps.Packaging.XpsDocument xpsDoc =
             new System.Windows.Xps.Packaging.XpsDocument(
                     path, System.IO.FileAccess.Read);
     if (xpsDoc == null) {
         throw new System.Exception("XpsDocumentfailed");
     }
     System.Windows.Documents.FixedDocumentSequence docSeq =
             xpsDoc.GetFixedDocumentSequence();
     if (docSeq == null) {
         throw new System.Exception("GetFixedDocumentSequence failed");
     }
     System.Windows.Documents.DocumentReferenceCollection drc = docSeq.References;
     int index = 0;
     foreach (System.Windows.Documents.DocumentReference dr in drc) {
         System.Windows.Documents.FixedDocument dp = dr.GetDocument(false);
         foreach (System.Windows.Documents.PageContent pc in dp.Pages) {
             System.Windows.Documents.FixedPage fixedPage = pc.GetPageRoot(false);
             double width = fixedPage.Width;
             double height = fixedPage.Height;
             System.Windows.Size sz = new System.Windows.Size(width, height);
             fixedPage.Measure(sz);
             fixedPage.Arrange(
                     new System.Windows.Rect(new System.Windows.Point(), sz));
             fixedPage.UpdateLayout();
             System.Windows.Media.Imaging.BitmapImage bitmap =
                     new System.Windows.Media.Imaging.BitmapImage();
             System.Windows.Media.Imaging.RenderTargetBitmap renderTarget =
                     new System.Windows.Media.Imaging.RenderTargetBitmap(
                         ceil(scale * width), ceil(scale * height), dpi, dpi,
                         System.Windows.Media.PixelFormats.Default);
             renderTarget.Render(fixedPage);
             System.Windows.Media.Imaging.BitmapEncoder encoder =
                 new System.Windows.Media.Imaging.PngBitmapEncoder();
             encoder.Frames.Add(
                     System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget));
             string filename = string.Format("{0}_{1}.png", out_path, index);
             System.IO.FileStream pageOutStream = new System.IO.FileStream(
                 filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
             encoder.Save(pageOutStream);
             pageOutStream.Close();
             System.Console.WriteLine(filename);
             ++index;
         }
     }
 }
        public static Image RenderLatex(string latex, int maxWidth)
        {
            var formula      = parser.Parse(latex);
            var renderer     = formula.GetRenderer(WpfMath.TexStyle.Display, 60.0, "Arial");
            var bitmapSource = renderer.RenderToBitmap(0, 0);
            var encoder      = new System.Windows.Media.Imaging.PngBitmapEncoder();

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapSource));

            MemoryStream stream = new MemoryStream();

            encoder.Save(stream);
            var rawRes = Image.FromStream(stream);

            return(maxWidth < rawRes.Width ? resizeImage(rawRes, new Size(maxWidth, maxWidth * rawRes.Height / rawRes.Width)) : rawRes);
        }
Exemplo n.º 21
0
 private byte[] BitmapSourceToByte(System.Windows.Media.Imaging.BitmapSource source)
 {
     try
     {
         var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
         var frame   = System.Windows.Media.Imaging.BitmapFrame.Create(source);
         encoder.Frames.Add(frame);
         var stream = new System.IO.MemoryStream();
         encoder.Save(stream);
         return(stream.ToArray());
     }
     catch (Exception ex)
     {
         return(new byte[0]);
     }
 }
Exemplo n.º 22
0
 /// <summary>
 /// Convert WriteableBitmap to BitmapImage.
 /// refer to https://stackoverflow.com/questions/14161665/how-do-i-convert-a-writeablebitmap-object-to-a-bitmapimage-object-in-wpf
 /// </summary>
 /// <param name="wbm"></param>
 /// <returns></returns>
 public static System.Windows.Media.Imaging.BitmapImage ConvertWriteablebitmapToBitmapimage(System.Windows.Media.Imaging.WriteableBitmap wbm)
 {
     System.Windows.Media.Imaging.BitmapImage bmpimg = new System.Windows.Media.Imaging.BitmapImage();
     using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
     {
         System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
         encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(wbm));
         encoder.Save(stream);
         bmpimg.BeginInit();
         bmpimg.CacheOption  = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
         bmpimg.StreamSource = stream;
         bmpimg.EndInit();
         bmpimg.Freeze();
     }
     return(bmpimg);
 }
Exemplo n.º 23
0
        private static void SaveImageAsPngFile(System.Windows.Media.Imaging.WriteableBitmap bitmap, string fileName, IntPtr hwnd, System.Windows.Int32Rect clippingRect)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException("Invalid bitmap!!");
            }

            if (!User32DllMethodsInvoker.IsWindow(hwnd))
            {
                throw new ArgumentException("Invalid window!!");
            }

            // クライアント矩形やユーザー定義クリッピング矩形で切り出した内容のみを保存する。
            var intersectRect = MyWin32InteropHelper.CalcClientIntersectRect(hwnd, clippingRect);

            System.Diagnostics.Debug.Assert(intersectRect.HasArea);

            var tempSubBitmap = new System.Windows.Media.Imaging.WriteableBitmap(intersectRect.Width, intersectRect.Height,
                                                                                 MyDeviceHelper.DefaultDpi, MyDeviceHelper.DefaultDpi, System.Windows.Media.PixelFormats.Pbgra32, null);

            try
            {
                tempSubBitmap.Lock();
                bitmap.CopyPixels(new System.Windows.Int32Rect(0, 0, intersectRect.Width, intersectRect.Height),
                                  tempSubBitmap.BackBuffer,
                                  tempSubBitmap.PixelWidth * tempSubBitmap.PixelHeight * 4,
                                  tempSubBitmap.PixelWidth * 4);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                tempSubBitmap.Unlock();
            }

            using (var stream = new System.IO.FileStream(fileName,
                                                         System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                //encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap));
                encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(tempSubBitmap));
                encoder.Save(stream);
            }
            tempSubBitmap = null;
        }
Exemplo n.º 24
0
        public static void GenerateImage(System.Windows.Controls.Viewbox control, Stream result)
        {
            //Set background to white
            //control.Background = System.Windows.Media.Brushes.White;

            System.Windows.Size controlSize = RetrieveDesiredSize(control);
            System.Windows.Rect rect        = new System.Windows.Rect(0, 0, controlSize.Width, controlSize.Height);

            System.Windows.Media.Imaging.RenderTargetBitmap rtb = new System.Windows.Media.Imaging.RenderTargetBitmap((int)controlSize.Width, (int)controlSize.Height, IMAGE_DPI, IMAGE_DPI, PixelFormats.Pbgra32);

            control.Arrange(rect);
            rtb.Render(control);

            System.Windows.Media.Imaging.PngBitmapEncoder png = new System.Windows.Media.Imaging.PngBitmapEncoder();
            png.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));
            png.Save(result);
        }
Exemplo n.º 25
0
        private void DrawToImage(FrameworkElement element)
        {
            element.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));
            element.Arrange(new Rect(element.DesiredSize));

            System.Windows.Media.Imaging.RenderTargetBitmap bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight,
                                                                                                                         120.0, 120.0, System.Windows.Media.PixelFormats.Pbgra32);
            bitmap.Render(element);

            System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap));

            using (Stream s = File.OpenWrite(@"C:\555.png"))
            {
                encoder.Save(s);
            }
        }
Exemplo n.º 26
0
        public static Bitmap ImageSourceToBitmap(System.Windows.Media.Imaging.BitmapSource bitmap)
        {
            Bitmap result = null;

            if (bitmap is System.Windows.Media.Imaging.BitmapSource)
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
                    enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap));
                    enc.Save(outStream);
                    outStream.Seek(0, SeekOrigin.Begin);
                    result = new Bitmap(outStream);
                }
            }

            return(result);
        }
Exemplo n.º 27
0
        static System.Drawing.Bitmap GetBitmap(string name)
        {
            var path = "pack://application:,,,/Images/" + name + ".png";

            var oUri  = new Uri(path, UriKind.RelativeOrAbsolute);
            var frame = System.Windows.Media.Imaging.BitmapFrame.Create(oUri);

            using (MemoryStream stream = new MemoryStream())
            {
                var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
                enc.Frames.Add(frame);
                enc.Save(stream);

                using (var tempBitmap = new System.Drawing.Bitmap(stream))
                {
                    // According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
                    // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
                    return(new System.Drawing.Bitmap(tempBitmap));
                }
            }
        }
Exemplo n.º 28
0
 public static Bitmap ToBitmap(this Media.Imaging.BitmapSource source)
 {
     Bitmap bitmap;
     using (MemoryStream outStream = new MemoryStream())
     {
         var enc = new Media.Imaging.PngBitmapEncoder();
         enc.Frames.Add(Media.Imaging.BitmapFrame.Create(source));
         enc.Save(outStream);
         bitmap = new Bitmap(outStream);
     }
     return bitmap;
 }
Exemplo n.º 29
0
        public static void CreateRemappedRasterFromVector(string xamlFile, System.Windows.Media.Color newColor, System.IO.Stream stream, double height, double width, string dynamicText)
        {
            string remapBase = "ReMapMe_";
            int    max       = 3;
            int    index     = 0;
            int    missed    = 0;
            Object temp      = null;
            string dynamText = "DynamicText";

            System.Windows.Controls.Canvas theVisual = System.Windows.Markup.XamlReader.Load(new System.IO.FileStream(xamlFile, System.IO.FileMode.Open)) as System.Windows.Controls.Canvas;

            if (null == theVisual)
            {
                return;
            }

            System.Windows.Size size = new System.Windows.Size(width, height);

            System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual();

            System.Windows.Media.VisualBrush visualBrush = new System.Windows.Media.VisualBrush(theVisual);

            System.Windows.Rect rect = new System.Windows.Rect(new System.Windows.Point(), size);

            while (missed < max)
            {
                string elementid = remapBase + index;

                temp = theVisual.FindName(elementid);

                if (null == temp)
                {
                    missed++;
                    index++;
                    continue;
                }

                System.Windows.Media.SolidColorBrush scb = ((temp as System.Windows.Shapes.Path).Fill as System.Windows.Media.SolidColorBrush);

                System.Windows.Media.Color c = scb.Color;
                c.B = newColor.B;
                c.R = newColor.R;
                c.G = newColor.G;

                scb.Color = c;
                index++;
            }

            theVisual.Arrange(rect);
            theVisual.UpdateLayout();

            using (System.Windows.Media.DrawingContext dc = drawingVisual.RenderOpen())
            {
                dc.DrawRectangle(visualBrush, null, rect);
            }

            if (!dynamText.IsNullOrWhitespace())
            {
                temp = theVisual.FindName(dynamText);
                if (null != temp)
                {
                    //do dynamic text shit
                }
            }

            System.Windows.Media.Imaging.RenderTargetBitmap render = new System.Windows.Media.Imaging.RenderTargetBitmap((int)height, (int)width, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
            render.Render(drawingVisual);

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

            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(render));

            encoder.Save(stream);

            stream.Flush();
            stream.Close();

            visualBrush   = null;
            drawingVisual = null;
            theVisual     = null;
            render        = null;
            encoder       = null;
        }
Exemplo n.º 30
0
        void Export(Dictionary <Area, AreaData> dic)
        {
            float[] totalArea = GetTotalArea(dic);
            AreaData[,] areaDataArray = NewAreaDataArray(dic);
            float[] limit = ElevationLimit(areaDataArray);
            //int highLimit = (int)(limit[1] - limit[0]);
            int areaArrayX   = areaDataArray.GetLength(0);
            int areaArrayY   = areaDataArray.GetLength(1);
            int areaPixelX   = high.x + 1;
            int areaPixelY   = high.y + 1;
            int outputImageX = (areaArrayX * areaPixelX);
            int outputImageY = (areaArrayY * areaPixelY);

            byte[] hightMap = new byte[outputImageY * outputImageX * 2];
            for (int areaY = 0; areaY < areaArrayY; ++areaY)
            {
                for (int areaX = 0; areaX < areaArrayX; ++areaX)
                {
                    //heightMap:Landscape=128:1m
                    //例:heightMapの値が35680=2912+0x800でUE4のLandscapeはスケール100の状態で22.75m
                    //UE4側でスケールを500にする想定とするとheightMapの値25.6で1m扱いとなる
                    //-1280m~1279m程度の表現が可能。
                    const float  ue4DefaultScale      = 100f;
                    const float  ue4ApplyScale        = 500f;
                    const float  hightMapPerLandscape = 128f;
                    const float  coefficient          = hightMapPerLandscape / (ue4ApplyScale / ue4DefaultScale);
                    const UInt16 ue4SeaLevel          = 0x8000;
                    AreaData     areaData             = areaDataArray[areaX, areaY];
                    if (areaData != null)
                    {
                        for (int y = 0; y < areaPixelY; ++y)
                        {
                            int i = ((areaY * areaPixelY + y) * outputImageX + (areaX * areaPixelX)) * 2;
                            for (int x = 0; x < areaPixelX; ++x)
                            {
                                float  height = areaData.elevation[x, y];
                                UInt16 v      = (UInt16)(height * coefficient + ue4SeaLevel);
                                hightMap[i++] = (byte)(v & 0xff);
                                hightMap[i++] = (byte)((v >> 8) & 0xff);
                            }
                        }
                    }
                    else
                    {
                        const float height = AreaData.elevationSeaLevel;
                        UInt16      v      = (UInt16)(height * coefficient + ue4SeaLevel);
                        byte        v0     = (byte)(v & 0xff);
                        byte        v1     = (byte)((v >> 8) & 0xff);
                        for (int y = 0; y < areaPixelY; ++y)
                        {
                            int i = ((areaY * areaPixelY + y) * outputImageX + (areaX * areaPixelX)) * 2;
                            for (int x = 0; x < areaPixelX; ++x)
                            {
                                hightMap[i++] = v0;
                                hightMap[i++] = v1;
                            }
                        }
                    }
                }
            }
            var bmp = System.Windows.Media.Imaging.BitmapImage.Create
                      (
                outputImageX, outputImageY, 96, 96,
                System.Windows.Media.PixelFormats.Gray16,
                System.Windows.Media.Imaging.BitmapPalettes.Gray16,
                hightMap,
                outputImageX * 16 / 8
                      );

            Microsoft.Win32.SaveFileDialog sd = new Microsoft.Win32.SaveFileDialog();
            sd.Filter   = "pngファイル(*.png)|*.png";
            sd.FileName = "heightMap(" + totalArea[0] + "," + totalArea[2] + ")-(" + totalArea[1] + "," + totalArea[3] + ")[" + limit[0] + "," + limit[1] + "].png";
            sd.Title    = "pngGファイル名を指定してください。";
            bool?result = sd.ShowDialog();

            if (result == true)
            {
                using (System.IO.FileStream stream = new System.IO.FileStream(sd.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                {
                    var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
                    encoder.Save(stream);
                }
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// 渲染字符串
        /// </summary>
        /// <param name="previewText"></param>
        /// <param name="backColor">背景色</param>
        /// <param name="foreColor">前景色</param>
        /// <param name="fontSize">font size in pixel</param>
        /// <returns></returns>
        public System.Drawing.Bitmap RenderString(string previewText, System.Drawing.Color backColor, System.Drawing.Color foreColor, int fontSize)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(previewText))
                {
                    if (_glyphTypeface.FamilyNames.Count == 0)
                    {
                        previewText = "no name";
                    }
                    else if (_glyphTypeface.FamilyNames.ContainsKey(CultureInfo.CurrentCulture))
                    {
                        previewText = _glyphTypeface.FamilyNames[CultureInfo.CurrentCulture];
                    }
                    else
                    {
                        previewText = _glyphTypeface.FamilyNames[_glyphTypeface.FamilyNames.Keys.First()];
                    }
                }

                var glyphIndexList = GetGlyphIndexList(previewText);
                if (glyphIndexList.Count <= 0)
                {
                    return(null);
                }
                var geometryList     = glyphIndexList.Select(glyphIndex => _glyphTypeface.GetGlyphOutline(glyphIndex, fontSize, 1d)).ToList();
                var advanceWidthList = glyphIndexList.Select(glyphIndex => _glyphTypeface.AdvanceWidths[glyphIndex]).ToList();

                var cellSize = new Size(fontSize, fontSize * _glyphTypeface.Height);

                var offsetX       = 0d;
                var offsetY       = fontSize * _glyphTypeface.Baseline;
                var drawingVisual = new System.Windows.Media.DrawingVisual();
                var brush         = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(foreColor.R, foreColor.G, foreColor.B));
                //var pen = new System.Windows.Media.Pen(brush, 0);
                using (var dc = drawingVisual.RenderOpen())
                {
                    for (var i = 0; i < geometryList.Count; i++)
                    {
                        var geometry     = geometryList[i];
                        var advanceWidth = advanceWidthList[i];
                        //if (geometry.IsEmpty()) continue;
                        dc.PushTransform(new System.Windows.Media.TranslateTransform(offsetX, offsetY));
                        dc.DrawGeometry(brush, null, geometry);
                        dc.Pop(); // get rid of the transform
                        offsetX += advanceWidth * cellSize.Width;
                    }
                }

                var bitWidth    = (int)Math.Ceiling(offsetX);
                var bitHeight   = (int)Math.Ceiling(cellSize.Height);
                var targetImage = new System.Windows.Media.Imaging.RenderTargetBitmap(bitWidth, bitHeight, Dpi, Dpi, System.Windows.Media.PixelFormats.Pbgra32);
                targetImage.Render(drawingVisual);

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

                //redraw to Bitmap
                var bmp = new System.Drawing.Bitmap(bitWidth, bitHeight);
                bmp.SetResolution(Dpi, Dpi);
                using (var graphics = System.Drawing.Graphics.FromImage(bmp))
                {
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphics.Clear(backColor);

                    using (var ms = new MemoryStream())
                    {
                        bmpEncoder.Save(ms);
                        graphics.DrawImage(System.Drawing.Image.FromStream(ms), new System.Drawing.PointF(0, 0));
                    }

                    graphics.Save();
                }

                return(bmp);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }