Exemple #1
0
        /// <summary>
        /// generate a barcode starts with MESCAP then followed with a random 8-digit number, then save it
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">event args</param>
        private void barcodeBT_Click(object sender, EventArgs e)
        {
            BarcodeEncoder generator = new BarcodeEncoder();
            string         ramdomNum = new Random().Next(0, 99999999).ToString();
            string         code      = "MESCAP" + ramdomNum;

            saveDialog = new SaveFileDialog();

            generator.IncludeLabel = true;
            generator.CustomLabel  = "MESCAP" + ramdomNum;
            WriteableBitmap image = generator.Encode(BarcodeFormat.Code39, code);

            saveDialog.Filter = "PNG File|*png";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                FileStream       stream        = new FileStream(saveDialog.FileName, FileMode.Create);
                PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
                bitmapEncoder.Frames.Add(BitmapFrame.Create(image));
                bitmapEncoder.Save(stream);
                MessageBox.Show("Successfully saved!");
            }
        }
Exemple #2
0
 /// <summary>
 /// Converts the given imageSource parameter to a file in the doc directory and returns an html string referencing this.
 /// </summary>
 /// <param name="imageSource">The ImageSource containing the image to convert.</param>
 /// <param name="filename">The wished filename (withouth the extension)</param>
 /// <param name="entityType"></param>
 /// <returns></returns>
 private string ConvertImageSource(BitmapFrame imageSource, string filename, EntityDocumentationPage entityDocumentationPage)
 {
     filename = filename + ".png";
     if (!_createdImages.Contains(filename))
     {
         var dir = Path.Combine(Path.Combine(_outputDir, OnlineHelp.HelpDirectory), entityDocumentationPage.DocDirPath);
         //create image file:
         if (!Directory.Exists(dir))
         {
             Directory.CreateDirectory(dir);
         }
         var file = Path.Combine(dir, filename);
         using (var fileStream = new FileStream(file, FileMode.Create))
         {
             var encoder = new PngBitmapEncoder();
             encoder.Frames.Add(imageSource);
             encoder.Save(fileStream);
         }
     }
     _createdImages.Add(filename);
     return(string.Format("<img src=\"{0}\" />", filename));
 }
Exemple #3
0
        private byte[] GetEncodedImageData(BitmapImage image)
        {
            byte[] result = null;

            BitmapEncoder encoder = new PngBitmapEncoder();

            using (MemoryStream stream = new MemoryStream())
            {
                encoder.Frames.Add(BitmapFrame.Create(image));
                encoder.Save(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = new byte[stream.Length];
                BinaryReader br = new BinaryReader(stream);

                br.Read(result, 0, (int)stream.Length);

                br.Close();

                stream.Close();
            }
            return(result);
        }
Exemple #4
0
        public static void ScreenCapture(Control control, string filename)
        {
            // The BitmapSource that is rendered with a Visual.
            control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            var size   = control.DesiredSize;
            var width  = (int)size.Width;
            var height = (int)size.Height;

            control.Arrange(new Rect(0, 0, width, height));
            var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

            rtb.Render(control);

            // Encoding the RenderBitmapTarget as a PNG file.
            var png = new PngBitmapEncoder();

            png.Frames.Add(BitmapFrame.Create(rtb));
            using (Stream stm = File.Create(filename))
            {
                png.Save(stm);
            }
        }
Exemple #5
0
        private void CreateScreenShot(UIElement visual, string file)//pour prendre des captures d'écran

        {
            double width = Convert.ToDouble(visual.GetValue(FrameworkElement.WidthProperty));

            double height = Convert.ToDouble(visual.GetValue(FrameworkElement.HeightProperty));



            if (double.IsNaN(width) || double.IsNaN(height))

            {
                throw new FormatException("Erreur !! ");
            }

            RenderTargetBitmap render = new RenderTargetBitmap(
                Convert.ToInt32(width),
                Convert.ToInt32(visual.GetValue(FrameworkElement.HeightProperty)), 96, 96, PixelFormats.Pbgra32);

            // Indicate which control to render in the image
            render.Render(visual);
            try
            {
                using (FileStream stream = new FileStream(file, FileMode.Create))

                {
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(render));
                    encoder.Save(stream);
                    //  WpfMessageBox.Show("Réussi", "Capture prise avec succés", MessageBoxButton.OK, WpfMessageBox.MessageBoxImage.Information);
                }
            }
            catch (Exception)
            {
                WpfMessageBox.Show("Erreur", "Echec de la sauvegarde !", MessageBoxButton.OK, WpfMessageBox.MessageBoxImage.Error);
                // WpfMessageBox.Show("Erreur", "Echec de la sauvegarde !", MessageBoxButton.OK, WpfMessageBox.MessageBoxImage.Error);
            }
        }
Exemple #6
0
        private static void OnIconBitmapSourceChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
        {
            var icon = source as BindableTaskbarIcon;

            if (icon == null)
            {
                return;
            }

            Icon oldIcon = icon.Icon;
            var  src     = e.NewValue as BitmapSource;

            if (src == null)
            {
                icon.Icon = null;
            }
            else
            {
                var enc = new PngBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(src));

                using (var ms = new MemoryStream())
                {
                    enc.Save(ms);
                    ms.Position = 0;

                    using (Bitmap bmp = (Bitmap)Bitmap.FromStream(ms))
                    {
                        icon.Icon = Icon.FromHandle(bmp.GetHicon());
                    }
                }
            }

            IntPtr iconHandle = oldIcon.Handle;

            oldIcon.Dispose();
            NativeMethods.DestroyIcon(iconHandle);
        }
        private void CreateSaveBitmap(Canvas canvas, string filename)
        {
            //Size size = new Size(window.Width, window.Height);
            //canvas.Measure(size);
            ////canvas.Arrange(new Rect(size));

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

            //SaveRTBAsPNG(rtb, filename);


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

            // needed otherwise the image output is black
            canvas.Measure(new System.Windows.Size((int)canvas.Width, (int)canvas.Height));
            canvas.Arrange(new Rect(new System.Windows.Size((int)canvas.Width, (int)canvas.Height)));

            renderBitmap.Render(canvas);

            //JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            PngBitmapEncoder encoder = new PngBitmapEncoder();

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

            using (FileStream file = File.Create(filename))
            {
                encoder.Save(file);
            }
        }
        public System.Drawing.Bitmap RenderIcon(string iconText)
        {
            var text = new FormattedText(
                iconText,
                this.CultureInfo,
                this.FlowDirection,
                this.typeface,
                this.fontSize,
                this.foreground);

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

            drawingContext.DrawText(text, new Point(2, 2));
            drawingContext.Close();

            var target = new RenderTargetBitmap(
                this.iconSize,
                this.iconSize,
                TrayIconDPI,
                TrayIconDPI,
                PixelFormats.Default);

            target.Clear();
            target.Render(drawingVisual);

            var enc = new PngBitmapEncoder();

            enc.Frames.Add(BitmapFrame.Create(target));

            using (var ms = new MemoryStream())
            {
                enc.Save(ms);
                ms.Position = 0;

                return((System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(ms));
            }
        }
        public void SaveScreenshotToDisk()
        {
            if (SelectedDeck == null ||
                DeckScreenshot == null)
            {
                return;
            }

            var invalid         = new string(Path.GetInvalidFileNameChars());
            var defaultFilename = invalid.Aggregate(DeckName, (current, c) => current.Replace(c.ToString(CultureInfo.InvariantCulture), "_"));

            defaultFilename += ".png";
            var dialog = new CommonSaveFileDialog
            {
                OverwritePrompt      = true,
                DefaultExtension     = ".png",
                DefaultFileName      = defaultFilename,
                EnsureValidNames     = true,
                Title                = "Save deck screenshot",
                AllowPropertyEditing = false,
                RestoreDirectory     = true,
                Filters              =
                {
                    new CommonFileDialogFilter("PNG", ".png")
                }
            };

            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                var filename = dialog.FileName;
                using (var fs = File.Create(filename))
                {
                    BitmapEncoder enc = new PngBitmapEncoder();
                    enc.Frames.Add(BitmapFrame.Create(DeckScreenshot));
                    enc.Save(fs);
                }
            }
        }
        private void TakeSnapshotOfWorld(object sender, RoutedEventArgs e)
        {
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)CameraImage.ActualWidth, (int)CameraImage.ActualHeight, 96.0, 96.0, PixelFormats.Pbgra32);
            DrawingVisual      dv           = new DrawingVisual();

            using (DrawingContext dc = dv.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(CameraImage);
                dc.DrawRectangle(brush, null, new Rect(new Point(), new Size(CameraImage.ActualWidth, CameraImage.ActualHeight)));
            }
            renderBitmap.Render(dv);

            BitmapEncoder encoder = new PngBitmapEncoder();

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


            var timestamp = DateTime.Now.ToString("yyyyMMddhhmmss");
            var myPhotos  = String.Format("{0}\\{1}", Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Photobooth");
            var fileName  = String.Format("KinectPhotobooth-{0}.png", timestamp);

            var path = System.IO.Path.Combine(myPhotos, fileName);

            try
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
                {
                    encoder.Save(fs);
                }


                encoder = null;
            }
            catch (System.IO.IOException)
            {
                Console.WriteLine("F**k");
            }
        }
Exemple #11
0
        private void ClipboardChanged(object sender, EventArgs e)
        {
            if (_shouldCaptureImage)
            {
                var imageFromClipboard = Clipboard.GetImage();
                if (imageFromClipboard != null)
                {
                    var resizedImage  = new TransformedBitmap(imageFromClipboard, new ScaleTransform(BUTTON_WIDTH / imageFromClipboard.PixelWidth, BUTTON_HEIGHT / imageFromClipboard.PixelHeight));
                    var bitmapEncoder = new PngBitmapEncoder();
                    bitmapEncoder.Frames.Add(BitmapFrame.Create(resizedImage));
                    var imageStream = new MemoryStream();
                    bitmapEncoder.Save(imageStream);
                    var keybitmap = KeyBitmap.FromStream(imageStream);

                    var clipboardItem = new ClipboardItem()
                    {
                        Bitmap    = imageFromClipboard,
                        KeyBitmap = keybitmap
                    };

                    _clipboardItems.Enqueue(clipboardItem);
                    while (_clipboardItems.Count > 5)
                    {
                        if (_clipboardItems.TryDequeue(out ClipboardItem item))
                        {
                        }
                    }

                    var deck = StreamDeck.OpenDevice();
                    int i    = 9;
                    foreach (var clipItem in _clipboardItems)
                    {
                        deck.SetKeyBitmap(i--, clipItem.KeyBitmap);
                    }
                }
                _shouldCaptureImage = false;
            }
        }
        public void ExportToPng(Uri path, Grid surface)
        {
            if (path == null)
            {
                return;
            }

            Transform transform = surface.LayoutTransform;

            surface.UseLayoutRounding = true;
            surface.LayoutTransform   = null;

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

            surface.Measure(size);
            surface.Arrange(new Rect(size));


            //PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.Transform.x


            using (FileStream outStream = new FileStream(path.LocalPath, FileMode.OpenOrCreate))
            {
                System.Drawing.Graphics graphics     = System.Drawing.Graphics.FromHwnd(IntPtr.Zero);
                RenderTargetBitmap      renderBitmap =
                    new RenderTargetBitmap(
                        (int)size.Width,
                        (int)size.Height,
                        graphics.DpiX,
                        graphics.DpiY,
                        PixelFormats.Pbgra32);
                renderBitmap.Render(surface);
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                encoder.Save(outStream);
            }
            surface.LayoutTransform = transform;
        }
Exemple #13
0
    public static Cursor CreatCursor(UIElement u, System.Windows.Point p)
    {
        Cursor c;

        /// move to the orignal point of parent
        u.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));
        u.Arrange(new Rect(0, 0,
                           u.DesiredSize.Width,
                           u.DesiredSize.Height));

        /// render the source to a bitmap image
        RenderTargetBitmap r =
            new RenderTargetBitmap(
                (int)u.DesiredSize.Width,
                (int)u.DesiredSize.Height,
                96, 96, PixelFormats.Pbgra32);

        r.Render(u);

        /// reset back to the orignal position
        u.Measure(new System.Windows.Size(0, 0));

        using (MemoryStream m = new MemoryStream())
        {
            /// use an encoder to transform to Bitmap
            PngBitmapEncoder e = new PngBitmapEncoder();
            e.Frames.Add(BitmapFrame.Create(r));
            e.Save(m);
            System.Drawing.Bitmap b =
                new System.Drawing.Bitmap(m);

            /// create cursor from Bitmap
            c = CreatCursor(b,
                            (int)p.X, (int)p.Y);
        }

        return(c);
    }
Exemple #14
0
        public void GeneratePreview(object parameter)
        {
            if (!(parameter is WallpaperRender render) || CurrentWallpaper == null)
            {
                return;
            }

            try
            {
                using (FileStream stream = File.Open(CurrentWallpaper.AbsolutePreviewPath, FileMode.Create))
                {
                    RenderTargetBitmap bmp = new RenderTargetBitmap((int)render.ActualWidth,
                                                                    (int)render.ActualHeight, 96, 96, PixelFormats.Pbgra32);

                    bmp.Render(render);

                    //截图保持正方形
                    var           size = (int)(render.ActualWidth > render.ActualHeight ? render.ActualHeight : render.ActualWidth);
                    var           x    = (int)(render.ActualWidth / 2 - size / 2);
                    var           y    = (int)(render.ActualHeight / 2 - size / 2);
                    CroppedBitmap crop = new CroppedBitmap(bmp, new Int32Rect(x, y, size, size));

                    PngBitmapEncoder coder = new PngBitmapEncoder
                    {
                        Interlace = PngInterlaceOption.Off
                    };
                    coder.Frames.Add(BitmapFrame.Create(crop));
                    coder.Save(stream);
                }

                CurrentWallpaper.NotifyOfPropertyChange(Wallpaper.AbsolutePreviewPathPropertyName);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                MessageBox.Show(ex.Message);
            }
        }
Exemple #15
0
        public static void SnapShotPng(UIElement source, String destination, Int32 zoom)
        {
            try
            {
                Double actualHeight = source.RenderSize.Height;
                Double actualWidth  = source.RenderSize.Width;

                Double renderHeight = actualHeight * zoom;
                Double renderWidth  = actualWidth * zoom;

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

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

                using (drawingContext)
                {
                    drawingContext.PushTransform(new ScaleTransform(zoom, zoom));
                    drawingContext.DrawRectangle(sourceBrush, null, new Rect(new System.Windows.Point(0, 0), new System.Windows.Point(actualWidth, actualHeight)));
                }

                renderTarget.Render(drawingVisual);

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

                using (FileStream stream = new FileStream(destination, FileMode.Create, FileAccess.Write))
                {
                    encoder.Save(stream);
                }
            }
            catch (Exception ex)
            {
                OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "Unable to export image", ex);
                AnalyticsService.GetInstance().SendEvent(AnalyticsService.AnalyticsAction.General, ex);
            }
        }
        private void MapSaveFile(object sender, RoutedEventArgs e)
        {
            if (MapFilteredListBox.SelectedItem != null)
            {
                Map         map = MapFilteredListBox.SelectedItem as Map;
                BitmapImage img = map.LoadImage();
                UIElement   elt = ((MappingWindow)attempt.Content).mapCanvas;

                PresentationSource source = PresentationSource.FromVisual(elt);
                RenderTargetBitmap rtb    = new RenderTargetBitmap((int)map.LoadImage().PixelWidth,
                                                                   (int)map.LoadImage().PixelHeight, 96, 96, PixelFormats.Default);

                VisualBrush    sourceBrush    = new VisualBrush(elt);
                DrawingVisual  drawingVisual  = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                using (drawingContext)
                {
                    drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0),
                                                                             new Point(elt.RenderSize.Width, elt.RenderSize.Height)));
                }
                rtb.Render(drawingVisual);

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

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter   = "Image file (*.png)|*.png";
                saveFileDialog.Title    = "Save Map as:";
                saveFileDialog.FileName = map.map_name;
                if (saveFileDialog.ShowDialog() == true)
                {
                    using (Stream fileStream = File.Create(saveFileDialog.FileName))
                    {
                        pngImage.Save(fileStream);
                    }
                }
            }
        }
Exemple #17
0
        //The map is saved when the window is closed
        public static void saveMap(AdditionalInfoPage AIPmapSection)
        {
            Rect   AIbounds      = VisualTreeHelper.GetDescendantBounds(AIPmapSection);
            var    AIFileName    = "MapModification_" + DateTime.Now.ToString("yyyyMMdd_hhss");
            var    desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            double dpi           = 96d;
            bool   isMapLoaded   = AIPmapSection.MapLoaded();

            //If a map was loaded and modifications were made, save the map
            if (AIbounds.ToString() != "Empty" && isMapLoaded)
            {
                //Check the bound of the map
                RenderTargetBitmap rtb = new RenderTargetBitmap((int)AIbounds.Width, (int)AIbounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);
                DrawingVisual      dv  = new DrawingVisual();

                using (DrawingContext dc = dv.RenderOpen())
                {
                    VisualBrush vb = new VisualBrush(AIPmapSection.AdditionalMap);
                    dc.DrawRectangle(vb, null, new Rect(new System.Windows.Point(), AIbounds.Size));
                }

                rtb.Render(dv);
                BitmapEncoder pngEncoder = new PngBitmapEncoder();
                pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

                try
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    pngEncoder.Save(ms);
                    ms.Close();
                    System.IO.File.WriteAllBytes(desktopFolder + "\\" + AIFileName + ".png", ms.ToArray());//Save the modified map as an image based on bounds of the map
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Exemple #18
0
        private void renderImageBtn_Click(object sender, RoutedEventArgs e)
        {
            if (txtPathOutput.Text.Length == 0)
            {
                MessageBox.Show("Please choose folder mockups!");
                return;
            }

            System.Drawing.Image img = System.Drawing.Image.FromFile(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) + @"\trai san dan ong.png");

            var rect   = new Rect(new Size(img.Width, img.Width));
            var visual = new DrawingVisual();

            using (var dc = visual.RenderOpen())
            {
                dc.DrawRectangle(new VisualBrush(canvas1), null, rect);
            }


            try
            {
                rectangle1.Stroke = Brushes.Transparent;

                FileStream         fs  = new FileStream(this.storage.PathOutput + "//output.png", FileMode.Create);
                RenderTargetBitmap bmp = new RenderTargetBitmap(
                    (int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(visual);

                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                encoder.Save(fs);
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sourcePlayer0.IsRunning)
                {
                    BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        sourcePlayer0.GetCurrentVideoFrame().GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pbe = new PngBitmapEncoder();
                    pbe.Frames.Add(BitmapFrame.Create(bs));
                    string t = DateTime.Now.ToLongTimeString().ToString();

                    t = t.Replace("-", "");
                    t = t.Replace(":", "");
                    string jpgName = GetImagePath() + "\\" + t + ".jpg";
                    if (File.Exists(jpgName))
                    {
                        File.Delete(jpgName);
                    }
                    using (Stream stream = File.Create(jpgName))
                    {
                        pbe.Save(stream);
                    }
                    //拍照
                    if (sourcePlayer0 != null && sourcePlayer0.IsRunning)
                    {
                        MessageBox.Show("照片储存地址:" + jpgName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常:" + ex.Message);
            }
        }
Exemple #20
0
        private void Export(StreamWriter allFormat)
        {
            StringBuilder str = new StringBuilder();

            str.Append("U4-");
            str.Append(comboBox1.Text);
            str.Append("-L");
            str.Append(level.ToString());
            //str.Append(".png");

            Bitmap           blah    = (Bitmap)pictureBox1.Image;
            BitmapSource     image   = _bitmapToSource(blah);
            FileStream       stream  = new FileStream(str.ToString() + ".png", FileMode.Create);
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            //TextBlock myTextBlock = new TextBlock();
            //myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);
            stream.Close();

            FileStream   fs = new FileStream(str.ToString() + ".txt", FileMode.Create, FileAccess.Write, FileShare.Write);
            StreamWriter sw = new StreamWriter(fs);

            sw.Write(textBox1.Text);
            if (allFormat != null)
            {
                //{| style="display:inline"
                //|
                allFormat.WriteLine("{| style=\"display:inline\"");
                allFormat.Write("| ");
                allFormat.WriteLine(textBox1.Text);
                allFormat.WriteLine("|}");
            }
            sw.Close();
            fs.Close();
        }
        private void btnExtract_Click(object sender, RoutedEventArgs e)
        {
            if (lstChars.SelectedIndex == -1)
            {
                return;
            }

            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
            sfd.RestoreDirectory = true;
            sfd.Title            = "Save Font Character";
            sfd.Filter           = "PNG Image (*.png)|*.png;|Raw Data (Debug) (*.bin)|*.bin;";
            if ((bool)sfd.ShowDialog())
            {
                switch (sfd.FilterIndex)
                {
                case 1:
                    FileStream    file    = new FileStream(sfd.FileName, FileMode.Create, System.IO.FileAccess.Write);
                    BitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(package.Fonts[fontslist.SelectedIndex].Characters[IndexFromSelectedItem()].Data.getImage()));
                    encoder.Save(file);
                    file.Close();
                    lstChars.UnselectAll();

                    WriteLog("Character successfully extracted to " + sfd.SafeFileName + ".");
                    break;

                case 2:
                    FileStream filex = new FileStream(sfd.FileName, FileMode.Create, System.IO.FileAccess.Write);
                    filex.Write(package.Fonts[fontslist.SelectedIndex].Characters[IndexFromSelectedItem()].Data.compressedData, 0,
                                package.Fonts[fontslist.SelectedIndex].Characters[IndexFromSelectedItem()].Data.dataSize);
                    filex.Close();
                    lstChars.UnselectAll();

                    WriteLog("Raw compressed character successfully extracted to " + sfd.SafeFileName + ".");
                    break;
                }
            }
        }
Exemple #22
0
        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            UserImage userImage = new UserImage();
            string    imageName = string.Empty;

            if (rbCats.IsChecked == true)
            {
                userImage.Category = "Cats";
            }
            else if (rbDogs.IsChecked == true)
            {
                userImage.Category = "Dogs";
            }
            else if (rbBirds.IsChecked == true)
            {
                userImage.Category = "Birds";
            }

            imageName = Guid.NewGuid().ToString() + ".jpg";

            string fullName = Environment.CurrentDirectory + @"\images\" + imageName;

            userImage.FileName = imageName;

            Uri         source   = new Uri(Environment.CurrentDirectory + @"\cropped.jpg");
            BitmapFrame image    = BitmapFrame.Create(source);
            String      filePath = fullName;

            var encoder = new PngBitmapEncoder();

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

            _context.UserImages.Add(userImage);
            _context.SaveChanges();
            Close();
        }
Exemple #23
0
        private void UnhandledExceptionOccurred(object sender, UnhandledExceptionEventArgs e)
        {
            Window win = Current.MainWindow;

            RenderTargetBitmap bmp = new RenderTargetBitmap(
                (int)win.Width,
                (int)win.Height,
                96,
                98,
                PixelFormats.Pbgra32
                );

            bmp.Render(win);

            string errorPath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "ErrorReports"
                );

            if (!Directory.Exists(errorPath))
            {
                Directory.CreateDirectory(errorPath);
            }

            BitmapEncoder encoder = new PngBitmapEncoder();

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

            string filePath = Path.Combine(
                errorPath,
                string.Format("{0:MMddyyyyhhmmss}.png", DateTime.Now)
                );

            using (Stream stream = File.Create(filePath))
            {
                encoder.Save(stream);
            }
        }
Exemple #24
0
        public unsafe BitmapImage Apply(BitmapImage original)
        {
            var bitmap = new WriteableBitmap(original);

            //Console.WriteLine(bitmap.BackBufferStride);
            //Console.WriteLine(bitmap.Format.BitsPerPixel.ToString());
            //Console.WriteLine(bitmap.BackBufferStride);
            //Console.WriteLine(bitmap.DpiX);

            //32
            //3204
            //801

            bitmap.Lock();

            byte *pBuffer = (byte *)bitmap.BackBuffer; // Pointer to actual image data in buffer (BGRA32 format (1 byte for each channel))

            Formula(pBuffer, bitmap, otherFunctionParams);

            bitmap.Unlock();

            // Convert WritableBitmap to BitmapImage
            BitmapImage bitmapImage = new BitmapImage();

            using (MemoryStream stream = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                encoder.Save(stream);
                bitmapImage.BeginInit();
                bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
                bitmapImage.Freeze();
            }

            return(bitmapImage);
        }
Exemple #25
0
        private void WriteOutImages()
        {
            string tmp_path     = SparkleLib.SparkleConfig.DefaultConfig.TmpPath;
            string pixmaps_path = Path.Combine(tmp_path, "Pixmaps");

            if (!Directory.Exists(pixmaps_path))
            {
                Directory.CreateDirectory(pixmaps_path);

                File.SetAttributes(tmp_path,
                                   File.GetAttributes(tmp_path) | FileAttributes.Hidden);
            }

            BitmapSource image     = SparkleUIHelpers.GetImageSource("user-icon-default");
            string       file_path = Path.Combine(pixmaps_path, "user-icon-default.png");

            using (FileStream stream = new FileStream(file_path, FileMode.Create))
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(image));
                encoder.Save(stream);
            }

            string [] actions = new string [] { "added", "deleted", "edited", "moved" };

            foreach (string action in actions)
            {
                BitmapSource image     = SparkleUIHelpers.GetImageSource("document-" + action + "-12");
                string       file_path = Path.Combine(pixmaps_path, "document-" + action + "-12.png");

                using (FileStream stream = new FileStream(file_path, FileMode.Create))
                {
                    BitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    encoder.Save(stream);
                }
            }
        }
        public CompressedBitmapSource(object source)
        {
            if (source == null)
            {
                return;
            }

            if (source is CompressedBitmapSource)
            {
                var compressedBitmap = (source as CompressedBitmapSource);
                Bytes  = compressedBitmap.Bytes;
                Width  = compressedBitmap.Width;
                Height = compressedBitmap.Height;
            }
            else if (source is BitmapSource)
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create((source as BitmapSource)));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    encoder.Save(memoryStream);
                    memoryStream.Flush();
                    Bytes = memoryStream.ToArray();
                }
                Width  = encoder.Frames[0].PixelWidth;
                Height = encoder.Frames[0].PixelHeight;
            }
            else if (source is byte[])
            {
                using (MemoryStream stream = new MemoryStream((byte[])source))
                {
                    var decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                    Width  = decoder.Frames[0].PixelWidth;
                    Height = decoder.Frames[0].PixelHeight;
                }
                Bytes = source as byte[];
            }
        }
        private void SendMailChart(string Subject, string Body, string From, string To, string Host, int Port, string Username, string Password)
        {
            try
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (chart != null)
                    {
                        RenderTargetBitmap screenCapture = chart.GetScreenshot(ShareScreenshotType.Chart);
                        outputFrame = BitmapFrame.Create(screenCapture);

                        if (screenCapture != null)
                        {
                            PngBitmapEncoder png = new PngBitmapEncoder();
                            png.Frames.Add(outputFrame);
                            System.IO.MemoryStream stream = new System.IO.MemoryStream();
                            png.Save(stream);
                            stream.Position = 0;

                            MailMessage theMail = new MailMessage(From, To, Subject, Body);
                            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(stream, "image.png");
                            theMail.Attachments.Add(attachment);

                            SmtpClient smtp  = new SmtpClient(Host, Port);
                            smtp.EnableSsl   = true;
                            smtp.Credentials = new System.Net.NetworkCredential(Username, Password);
                            string token     = Instrument.MasterInstrument.Name + ToDay(Time[0]) + " " + ToTime(Time[0]) + CurrentBar.ToString();

                            Print("Sending Mail!");
                            smtp.SendAsync(theMail, token);
                        }
                    }
                }));
            }
            catch (Exception ex) {
                Print("Sending Chart email failed -  " + ex);
            }
        }
Exemple #28
0
        private void SaveImage_Button_Click(object sender, RoutedEventArgs e)
        {
            if (MergerPreview_Image.Source != null)
            {
                DebugHelper.WriteLine("Merger: Saving image...");

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title            = "Save Image";
                saveFileDialog.FileName         = "Merger";
                saveFileDialog.InitialDirectory = FProp.Default.FOutput_Path;
                saveFileDialog.Filter           = "PNG Files (*.png)|*.png";
                if (saveFileDialog.ShowDialog() == true)
                {
                    string path = saveFileDialog.FileName;
                    using (var fileStream = new FileStream(path, FileMode.Create))
                    {
                        PngBitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create((BitmapSource)MergerPreview_Image.Source));
                        encoder.Save(fileStream);

                        if (File.Exists(path))
                        {
                            DebugHelper.WriteLine("Merger: Image saved at " + path);

                            new UpdateMyConsole(Path.GetFileNameWithoutExtension(path), CColors.Blue).Append();
                            new UpdateMyConsole(" successfully saved", CColors.White, true).Append();
                        }
                        else //just in case
                        {
                            DebugHelper.WriteLine("Merger: Image couldn't be saved at " + path);

                            new UpdateMyConsole("Bruh moment\nCouldn't save ", CColors.White).Append();
                            new UpdateMyConsole(Path.GetFileNameWithoutExtension(path), CColors.Blue, true).Append();
                        }
                    }
                }
            }
        }
        public static bool SaveAsPng(BitmapSource image)
        {
            if (image == null)
            {
                return(false);
            }

            string fileName = null;

            var saveFileDialog = new SaveFileDialog();

            saveFileDialog.AddExtension = true;
            saveFileDialog.Filter       = "Image Files(*.png) | *.png";
            if (!saveFileDialog.ShowDialog() == true)
            {
                return(false);
            }

            fileName = saveFileDialog.FileName;

            if (fileName == null)
            {
                return(false);
            }

            var encoder = new PngBitmapEncoder();

            BitmapFrame frame = BitmapFrame.Create(image);

            encoder.Frames.Add(frame);

            using (var stream = File.Create(fileName))
            {
                encoder.Save(stream);
            }

            return(true);
        }
Exemple #30
0
        // Save a control's image.
        private void SaveControlImage(FrameworkElement control,
                                      string filename)
        {
            // Get the size of the Visual and its descendants.
            Rect rect = VisualTreeHelper.GetDescendantBounds(control);

            // Make a DrawingVisual to make a screen
            // representation of the control.
            DrawingVisual dv = new DrawingVisual();

            // Fill a rectangle the same size as the control
            // with a brush containing images of the control.
            using (DrawingContext ctx = dv.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(control);
                ctx.DrawRectangle(brush, null, new Rect(rect.Size));
            }

            // Make a bitmap and draw on it.
            int width              = (int)control.ActualWidth;
            int height             = (int)control.ActualHeight;
            RenderTargetBitmap rtb = new RenderTargetBitmap(
                width, height, 96, 96, PixelFormats.Pbgra32);

            rtb.Render(dv);

            // Make a PNG encoder.
            PngBitmapEncoder encoder = new PngBitmapEncoder();

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

            // Save the file.
            using (FileStream fs = new FileStream(filename,
                                                  FileMode.Create, FileAccess.Write, FileShare.None))
            {
                encoder.Save(fs);
            }
        }