private void Clicked(object sender, RoutedEventArgs e)
        {
            var result = Clipboard.GetImage();
            if (result == null)
            {
                MessageBox.Show("No image");
                return;
            }

            var directorypath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Screendumps");
            var filePath = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg";

            var directory = new DirectoryInfo(directorypath);
            if (!directory.Exists)
            {
                directory.Create();
            }

            using (var stream = new FileStream(Path.Combine(directorypath,filePath), FileMode.Create))
            {
                var encode = new JpegBitmapEncoder();
                encode.QualityLevel = 100;
                encode.Frames.Add(BitmapFrame.Create(result));
                encode.Save(stream);
            }

            Clipboard.SetText(Path.Combine(directorypath,filePath));
        }
示例#2
0
        public static void SaveImageCapture(BitmapSource bitmap)
        {
            var encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;

            // Configure save file dialog box
            var dlg = new Microsoft.Win32.SaveFileDialog
            {
                FileName = "Image",
                DefaultExt = ".Jpg",
                Filter = "Image (.jpg)|*.jpg"
            };

            // Show save file dialog box
            var result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save Image
                string filename = dlg.FileName;
                var fstream = new FileStream(filename, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();
            }
        }
        /// <summary>
        /// Converts an <see cref="ImageSource"/> to an array of bytes.
        /// </summary>
        /// <param name="image"><see creConvertImageSourceToByteArrayf="ImageSource"/> to convert.</param>
        /// <returns>Array of bytes.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="image"/> is <c>null</c>.</exception>
        public static byte[] ConvertImageSourceToByteArray(this ImageSource image)
        {
            Argument.IsNotNull("image", image);

            byte[] result;
            BitmapFrame bitmapFrame = null;

            var encoder = new JpegBitmapEncoder();
            var bitmapSource = (BitmapSource)image;

            bitmapFrame = BitmapFrame.Create(bitmapSource);

            encoder.Frames.Add(bitmapFrame);

            using (var memoryStream = new MemoryStream())
            {
                encoder.Save(memoryStream);

                result = memoryStream.ToArray();

                encoder.Frames.Clear();
            }

            // Force garbage collection to prevent lots of memory usage
            GC.WaitForPendingFinalizers();
            GC.Collect();

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

                using (var stream = new MemoryStream())
                {
                    bitmapEncoder.Save(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.StreamSource = stream;
                    bitmapImage.EndInit();
                }
                var encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
                byte[] data = null;
                using (var ms = new MemoryStream())
                {
                    encoder.Save(ms);
                    data = ms.ToArray();
                }
                return data;
            }
            return null;
        }
        /// <summary>
        /// Scripter: YONGTOK KIM
        /// Description : Save the image to the file.
        /// </summary>

        public static string SaveImageCapture(BitmapSource bitmap)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;


            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Image"; // Default file name
            dlg.DefaultExt = ".Jpg"; // Default file extension
            dlg.Filter = "Image (.jpg)|*.jpg"; // Filter files by extension

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

            // Process save file dialog box results
            if (result == true)
            {
                // Save Image
                string filename = dlg.FileName;
                FileStream fstream = new FileStream(filename, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();

                return filename;
            }

            return null;
        }
 public static void ToImageFile(this Visual theVisual, string fileName)
 {
     BitmapEncoder encoder;
     switch (Path.GetExtension(fileName).ToLower())
     {
         case ".jpg":
         case ".jpeg":
             encoder = new JpegBitmapEncoder();
             break;
         case ".png":
             encoder = new PngBitmapEncoder();
             break;
         case ".bmp":
             encoder = new BmpBitmapEncoder();
             break;
         case ".gif":
             encoder = new GifBitmapEncoder();
             break;
         case ".tiff":
             encoder = new TiffBitmapEncoder();
             break;
         default:
             throw new EncoderFallbackException("The Specified Filename is not a known image type.  Supported image formats are jpeg, png, bmp, gif, and tiff.");
     }
     encoder.Frames.Add(BitmapFrame.Create(theVisual.ToBitmapSource()));
     using (var stream = new FileStream(fileName, FileMode.Create)) encoder.Save(stream);
 }
示例#9
0
        /// <summary>
        /// Sets wallpaper and style
        /// WinowsAPI Call
        /// </summary>
        /// <param name="image"></param>
        /// <param name="style"></param>
        public static void SetWallPaper(BitmapImage image, Style style)
        {
            if (image != null)
            {
                string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper");

                //image.Save(tempPath, System.Drawing.Imaging.ImageFormat.Jpeg)
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();

                try
                {
                    encoder.Frames.Add(BitmapFrame.Create(image));
                }
                catch { }

                using(Stream fs = new FileStream(tempPath, FileMode.Create))
                {
                    encoder.Save(fs);
                }

                SetWallPaperStyle(style);

                //Win API Call
                SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWINIINICHANGE);
            }
        }
        private void btnCapture_Click(object sender, RoutedEventArgs e)
        {
            //captureElement. 怎么抓取高清的原始图像
            //能不能抓视频。
            //todo:怎么只抓取一部分
            RenderTargetBitmap bmp = new RenderTargetBitmap(
                (int)captureElement.ActualWidth,
                (int)captureElement.ActualHeight,
                96, 96, PixelFormats.Default);

            //为避免抓不全的情况,需要在Render之前调用Measure、Arrange
            //为避免VideoCaptureElement显示不全,需要把
            //VideoCaptureElement的Stretch="Fill"
            captureElement.Measure(captureElement.RenderSize);
            captureElement.Arrange(new Rect(captureElement.RenderSize));
            bmp.Render(captureElement);

            BitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            using (MemoryStream ms = new MemoryStream())
            {
                encoder.Save(ms);
                CaptureData = ms.ToArray();
            }
            //captureElement.Pause();
            //todo:自己完成重拍的代码
            DialogResult = true;
        }
示例#11
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);
            }
        }
示例#12
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);
        }
示例#13
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);
            });
        }
示例#14
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);
            }
        }
示例#15
0
        public static byte[] GetScreenShot(this UIElement source, double scale, int quality)
        {
            double renderHeight = source.RenderSize.Height * scale;
            double renderWidth = source.RenderSize.Width * scale;

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

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

            using (drawingContext)
            {
                drawingContext.PushTransform(new ScaleTransform(scale, scale));
                drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(source.RenderSize.Width, source.RenderSize.Height)));
            }
            renderTarget.Render(drawingVisual);
            JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
            jpgEncoder.QualityLevel = quality;
            jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

            Byte[] image;
            using (MemoryStream outputStream = new MemoryStream())
            {
                jpgEncoder.Save(outputStream);
                image = outputStream.ToArray();
            }
            return image;
        }
示例#16
0
        public RecordedVideoFrame(ColorImageFrame colorFrame)
        {
            if (colorFrame != null)
            {
                byte[] bits = new byte[colorFrame.PixelDataLength];
                colorFrame.CopyPixelDataTo(bits);

                int BytesPerPixel = colorFrame.BytesPerPixel;
                int Width = colorFrame.Width;
                int Height = colorFrame.Height;

                var bmp = new WriteableBitmap(Width, Height, 96, 96, PixelFormats.Bgr32, null);
                bmp.WritePixels(new System.Windows.Int32Rect(0, 0, Width, Height), bits, Width * BytesPerPixel, 0);
                JpegBitmapEncoder jpeg = new JpegBitmapEncoder();
                jpeg.Frames.Add(BitmapFrame.Create(bmp));
                var SaveStream = new MemoryStream();
                jpeg.Save(SaveStream);
                SaveStream.Flush();
                JpegData = SaveStream.ToArray();
            }
            else
            {
                return;
            }
        }
        private static void adicionaMetadadosNaImagem(ItemDePauta item)
        {
            String caminhoArquivoOrigem = Path.Combine(ConfigurationManager.AppSettings["caminhoEntrada"], item.nomeArquivoImagem);
            String caminhoSaida = Path.Combine(ConfigurationManager.AppSettings["caminhoSaida"],
                item.nomeImagemNaPauta + "_" + item.nomeArquivoImagem);

            using (Stream file = File.Open(caminhoArquivoOrigem, FileMode.Open, FileAccess.ReadWrite)) {

                BitmapDecoder decoder = BitmapDecoder.Create(file, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();

                if (decoder.Frames[0] != null && decoder.Frames[0].Metadata != null) {

                    BitmapFrame frameCopy = (BitmapFrame)decoder.Frames[0].Clone();
                    BitmapMetadata metadata = decoder.Frames[0].Metadata.Clone() as BitmapMetadata;

                    try {
                        metadata.SetQuery("/xmp/dc:description/x-default", item.descricao);
                    } catch (Exception) {
                        metadata.SetQuery("/xmp/dc:description", item.descricao);
                    }
                    metadata.SetQuery("System.Keywords", item.palavrasChave);
                    metadata.Copyright = item.copyright;

                    encoder.Frames.Add(BitmapFrame.Create(frameCopy, frameCopy.Thumbnail, metadata, frameCopy.ColorContexts));

                    using (Stream outputFile = File.Open(caminhoSaida, FileMode.Create, FileAccess.ReadWrite)) {
                        encoder.Save(outputFile);
                    }
                }

            }
        }
示例#18
0
        /// <summary>
        /// Store into the compiled folder the user photo used to retrieve user information
        /// </summary>
        /// <param name="faceImageSource">face image source</param>
        /// <param name="imageFileName">face image name</param>
        /// <returns>1 if store success, 0 otherwise</returns>
        public static int SaveUserImage(BitmapSource faceImageSource, string imageFileName)
        {
            int resultCode = 1;

            if (File.Exists(imageFileName))
            {
                File.Delete(imageFileName);
            }

            using (FileStream saveSnapshotStream = new FileStream(imageFileName, FileMode.CreateNew))
            {
                try
                {
                    JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
                    jpgEncoder.QualityLevel = 100;
                    jpgEncoder.Frames.Add(BitmapFrame.Create(faceImageSource));
                    jpgEncoder.Save(saveSnapshotStream);

                    saveSnapshotStream.Flush();
                    saveSnapshotStream.Close();
                    saveSnapshotStream.Dispose();
                }
                catch (Exception e)
                {
                     resultCode = 0;
                }
            }

            return resultCode;
        }
示例#19
0
        /// 
        /// Gets a JPG "screenshot" of the current UIElement 
        /// 
        /// UIElement to screenshot 
        /// Scale to render the screenshot 
        /// JPG Quality 
        /// Byte array of JPG data 
        public byte[] GetJpgImage(double scale, int quality, int dpi)
        {
            double actualHeight = this.RootVisual.RenderSize.Height;
            double actualWidth = this.RootVisual.RenderSize.Width;

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

            RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, dpi, dpi, PixelFormats.Pbgra32);
            VisualBrush sourceBrush = new VisualBrush(this.RootVisual);

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

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

            renderTarget.Render(drawingVisual);
            JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
            jpgEncoder.QualityLevel = quality;
            jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

            Byte[] _imageArray;
            using (MemoryStream outputStream = new MemoryStream())
            {
                jpgEncoder.Save(outputStream);
                _imageArray = outputStream.ToArray();
            }

            return _imageArray;
        }
示例#20
0
        private static BitmapEncoder GetBitmapEncoder(ImageContentType imageContentType)
        {
            BitmapEncoder bitmapEncoder;

            switch (imageContentType)
            {
                case ImageContentType.ImageBmpContentType:
                    bitmapEncoder = new BmpBitmapEncoder();
                    break;
                case ImageContentType.ImageGifContentType:
                    bitmapEncoder = new GifBitmapEncoder();
                    break;
                case ImageContentType.ImageJpegContentType:
                    bitmapEncoder = new JpegBitmapEncoder();
                    break;
                case ImageContentType.ImageTiffContentType:
                    bitmapEncoder = new TiffBitmapEncoder();
                    break;
                case ImageContentType.ImagePngContentType:
                    bitmapEncoder = new PngBitmapEncoder();
                    break;
                default:
                    bitmapEncoder = new PngBitmapEncoder();
                    break;
            }
            return bitmapEncoder;
        }
        public static void SaveAsJpg(this BitmapSource source, string fileName, int quality)
        {
            var encoder = new JpegBitmapEncoder();
            encoder.QualityLevel = quality;

            SaveBitmapSourceToFile.Save(fileName, encoder, source);
        }
示例#22
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();
 }
示例#23
0
 /// <summary>
 /// </summary>
 /// <param name="source"> </param>
 /// <param name="scale"> </param>
 /// <param name="quality"> </param>
 /// <returns> </returns>
 public static byte[] GetJpgImage(UIElement source, double scale, int quality)
 {
     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 Point(actualWidth, actualHeight)));
     }
     renderTarget.Render(drawingVisual);
     var jpgEncoder = new JpegBitmapEncoder
     {
         QualityLevel = quality
     };
     jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
     Byte[] imageArray;
     using (var outputStream = new MemoryStream())
     {
         jpgEncoder.Save(outputStream);
         imageArray = outputStream.ToArray();
     }
     return imageArray;
 }
示例#24
0
        public void CustomeColorizer(string saveLocation, List<Colorizer> colorpalette)
        {
            if (_data == null)
                throw new InvalidDataException("You must Solve the case First!");

            if (colorpalette.Count <= 1)
                throw new InvalidDataException("You must choose at least 2 Colors");

            PixelFormat pf = PixelFormats.Rgb24;
            const double dpi = 96;
            int rawStride = (_width*pf.BitsPerPixel + 7)/8;
            var pixelData = new byte[rawStride*_height];

            foreach (Colorizer colorizer in colorpalette)
            {
                for (int i = 0; i < _data.Length; i++)
                {
                    if (Helper.IsInBetween(_data[i], colorizer.Min, colorizer.Max))
                    {
                        SetPixel((i%_width), (i/_width), colorizer.Color, ref pixelData, rawStride);
                    }
                }
            }

            BitmapSource bitmap = BitmapSource.Create(_width, _height, dpi, dpi, pf, null, pixelData, rawStride);

            var stream = new FileStream(saveLocation, FileMode.Create);
            var encoder = new JpegBitmapEncoder {QualityLevel = 100};
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(stream);
            stream.Close();
        }
示例#25
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();
            }
        }
        // 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();
                }
            }
        }
        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);
        }
示例#28
0
        public static BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            BitmapImage res =new BitmapImage();

            try
            {
               BitmapSource retval = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                             hBitmap,
                             IntPtr.Zero,
                             Int32Rect.Empty,
                             BitmapSizeOptions.FromEmptyOptions());
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                MemoryStream memoryStream = new MemoryStream();
                encoder.Frames.Add(BitmapFrame.Create(retval));
                encoder.Save(memoryStream);



               res.BeginInit();
               res.StreamSource = new MemoryStream(memoryStream.ToArray());
               res.EndInit();
            }
            finally
            {
                DeleteObject(hBitmap);
            }

            return res;
      }
示例#29
0
 public int AddMedium(string name, object obj)
 {
     var media = db.CreateObject<medium>();
     if (name == "Image")
     {
         byte[] img;
         JpegBitmapEncoder encoder = new JpegBitmapEncoder();
         encoder.Frames.Add(BitmapFrame.Create(obj as BitmapSource));
         using (MemoryStream ms = new MemoryStream())
         {
             encoder.Save(ms);
             img = ms.ToArray();
         }
         media.media_type_id = 1;
         media.@object = img;
     }
     else if (name == "Movie")
     {
         media.media_type_id = 2;
         media.@object = System.Text.Encoding.UTF8.GetBytes(obj as string);
     }
     else
     {
         media.media_type_id = 3;
         //BinaryFormatter bf = new BinaryFormatter();
         //MemoryStream ms = new MemoryStream();
         //bf.Serialize(ms, obj);
         //media.@object = ms.ToArray();
         media.@object = System.Text.Encoding.UTF8.GetBytes(obj as string);
     }
     db.media.AddObject(media);
     db.SaveChanges();
     return (int)media.id;
 }
示例#30
0
        private static MemoryStream SaveDrawingImage(ImageSource drawingImage)
        {
            var image = new Image
            {
                Source = drawingImage
            };

            image.Arrange(new Rect(0, 0, drawingImage.Width, drawingImage.Height));

            var settings = Settings.Default;

            var renderTargetBitmap = new RenderTargetBitmap((int)drawingImage.Width, (int)drawingImage.Height, settings.ImageDPI, settings.ImageDPI, PixelFormats.Default);
            renderTargetBitmap.Render(image);

            Settings.Default.Save();

            var encoder = new JpegBitmapEncoder
            {
                QualityLevel = settings.JpgQuality
            };

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

            var memoryStream = new MemoryStream();

            encoder.Save(memoryStream);

            return memoryStream;
        }
        /// <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);
            }
        }
        /// <summary>
        ///     Resizes the image presented by the <paramref name="imageData"/> to a <paramref name="newSize"/>.
        /// </summary>
        /// <param name="imageData">
        ///     The binary data of the image to resize.
        /// </param>
        /// <param name="newSize">
        ///     The size to which to resize the image.
        /// </param>
        /// <param name="keepAspectRatio">
        ///     A flag indicating whether to save original aspect ratio.
        /// </param>
        /// <returns>
        ///     The structure which contains binary data of resized image and the actial size of resized image depending on <paramref name="keepAspectRatio"/> value.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        ///     An error occurred during resizing the image.
        /// </exception>
        public static Task<ImageInfo> ResizeAsync(this byte[] imageData, Size newSize, bool keepAspectRatio)
        {
            var result = new ImageInfo();
            var image = imageData.ToBitmap();
            var percentWidth = (double) newSize.Width/(double) image.PixelWidth;
            var percentHeight = (double) newSize.Height/(double) image.PixelHeight;

            ScaleTransform transform;
            if (keepAspectRatio)
            {
                transform = percentWidth < percentHeight
                                ? new ScaleTransform {ScaleX = percentWidth, ScaleY = percentWidth}
                                : new ScaleTransform {ScaleX = percentHeight, ScaleY = percentHeight};
            }
            else
            {
                transform = new ScaleTransform {ScaleX = percentWidth, ScaleY = percentHeight};
            }

            var resizedImage = new TransformedBitmap(image, transform);

            using (var memoryStream = new MemoryStream())
            {
                var jpegEncoder = new JpegBitmapEncoder();
                jpegEncoder.Frames.Add(BitmapFrame.Create(resizedImage));
                jpegEncoder.Save(memoryStream);

                result.Data = memoryStream.ToArray();
                result.Size = new Size(resizedImage.PixelWidth, resizedImage.PixelHeight);
            }

            return Task.FromResult(result);
        }
示例#33
0
        private void SaveRTBAsJPG(RenderTargetBitmap bmp, string filename)
        {
            var enc = new System.Windows.Media.Imaging.JpegBitmapEncoder();

            enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
            using (var stm = System.IO.File.Create(filename))
            {
                enc.Save(stm);
            }
        }
        //public 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);
        //    }
        //}

        public static void SaveRTBAsPNG(RenderTargetBitmap bmp, Stream stream)
        {
            var enc = new System.Windows.Media.Imaging.JpegBitmapEncoder();

            enc.QualityLevel = 100;
            enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
            //using (var stm = System.IO.File.Create(filename))
            //{
            enc.Save(stream);
            //}
        }
示例#35
0
        public void SaveFrameworkElementToImage(FrameworkElement ui, string filename)
        {
            System.IO.FileStream ms = new System.IO.FileStream(filename, System.IO.FileMode.Create);
            System.Windows.Media.Imaging.RenderTargetBitmap bmp = new System.Windows.Media.Imaging.RenderTargetBitmap((int)ui.ActualWidth, (int)ui.ActualHeight, 96d, 96d, System.Windows.Media.PixelFormats.Pbgra32);
            bmp.Render(ui);
            System.Windows.Media.Imaging.JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
            encoder.Save(ms);
            ms.Close();

            //File.Copy(filename, filename, true);
        }
示例#36
0
        static public void TransformSave(BitmapSource bi, double scale, int quality, string filename)
        {
            var tr = new ScaleTransform(scale, scale);
            TransformedBitmap tb = new TransformedBitmap(bi, tr);
            //if (File.Exists(filename)) File.Delete(filename);
            var stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
            JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();

            encoder.QualityLevel = quality;
            encoder.Frames.Add(BitmapFrame.Create(tb));
            encoder.Save(stream);
            stream.Close();
        }
示例#37
0
        public void SaveFrameworkElementToImage(FrameworkElement ui, string filelocation, string filename)
        {
            System.IO.FileStream ms = new System.IO.FileStream(filename, System.IO.FileMode.Create);
            System.Windows.Media.Imaging.RenderTargetBitmap bmp = new System.Windows.Media.Imaging.RenderTargetBitmap
                                                                      ((int)ui.ActualWidth, (int)ui.ActualHeight, 96d, 96d, System.Windows.Media.PixelFormats.Pbgra32);
            bmp.Render(ui);
            System.Windows.Media.Imaging.JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
            encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
            encoder.Save(ms);
            ms.Close();
            string fs = AppDomain.CurrentDomain.BaseDirectory + "\\waveimage\\" + filelocation;

            if (!File.Exists(fs))
            {
                Directory.CreateDirectory(fs);
            }
            File.Copy(filename, fs + "\\" + filename + ".jpg", true);
        }
        /// <summary>
        /// 画像ファイルを保存
        /// </summary>
        private void SaveImage()
        {
            // ピクチャフォルダのスクリーンショットフォルダ
            string saveFolder   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Screenshots");
            string saveFilePath = Path.Combine(saveFolder, $"スクショ{DateTime.Now:yyyyMMdd-HHmmss}.jpeg");

            if (!Directory.Exists(saveFolder))
            {
                // 保存先フォルダが無ければ作成
                _ = Directory.CreateDirectory(saveFolder);
            }

            // 画像ファイル保存
            using Stream stream = new FileStream(saveFilePath, FileMode.Create);
            var encoder = new MIMG.JpegBitmapEncoder();

            encoder.Frames.Add(MIMG.BitmapFrame.Create((MIMG.BitmapSource)CaptureImage.Source));
            encoder.Save(stream);
        }
示例#39
0
        public void ExportToImage(string fileName)
        {
            //myInkCanvas.
            //Rectangle fillBackground = new Rectangle
            //{
            //    Width = 6646,
            //    Height = 3940,
            //    Fill = Brushes.White
            //};



            var rtb = new RenderTargetBitmap((int)myInkCanvas.ActualWidth,
                                             (int)myInkCanvas.ActualHeight,
                                             96d, 96d,
                                             PixelFormats.Pbgra32 // pixelformat
                                             );

            //rtb.Render(fillBackground);
            rtb.Render(myInkCanvas);

            //filename += ".jpg";
            var enc = new System.Windows.Media.Imaging.JpegBitmapEncoder();

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

            using (var stm = System.IO.File.Create(fileName))
            {
                enc.Save(stm);
            }

            //Rect bounds = VisualTreeHelper.GetDescendantBounds(myInkCanvas);
            //double dpi = 96d;

            //RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);
            //DrawingVisual dv = new DrawingVisual();
            //using (DrawingContext dc = dv.RenderOpen())
            //{
            //    VisualBrush vb = new VisualBrush(myInkCanvas);
            //    dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
            //}
            //rtb.Render(dv);

            //BitmapEncoder pngEncoder = new PngBitmapEncoder();
            //pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
            //using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            //{
            //    pngEncoder.Save(ms);
            //    System.IO.File.WriteAllBytes(fileName, ms.ToArray());
            //}

            //RenderTargetBitmap targetBitmap =
            //        new RenderTargetBitmap((int)myInkCanvas.ActualWidth,
            //                               (int)myInkCanvas.ActualHeight,
            //                               96d, 96d,
            //                               PixelFormats.Default);
            //    targetBitmap.Render(myInkCanvas);

            //    BitmapEncoder encoder = new BmpBitmapEncoder();
            //    encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
            //    using (FileStream fs = File.Open(fileName, FileMode.OpenOrCreate))
            //    {
            //        encoder.Save(fs);
            //    }
        }
示例#40
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);
        }