Ejemplo n.º 1
0
        /// <summary>
        /// Chuyển đổi BitmapSource thành Bitmap
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static System.Drawing.Bitmap GetBitmap(BitmapSource source)
        {
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap
            (
              source.PixelWidth,
              source.PixelHeight,
              System.Drawing.Imaging.PixelFormat.Format32bppRgb
            );

            System.Drawing.Imaging.BitmapData data = bmp.LockBits
            (
                new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size),
                System.Drawing.Imaging.ImageLockMode.WriteOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppRgb
            );

            source.CopyPixels
            (
              Int32Rect.Empty,
              data.Scan0,
              data.Height * data.Stride,
              data.Stride
            );

            bmp.UnlockBits(data);

            return bmp;
        }
Ejemplo n.º 2
0
        public HaloScreenshot(string tempImageLocation, TabItem tabItem)
        {
            InitializeComponent();

            // Convert DDS to BitmapImage
            _bitmapImage = DDSConversion.Deswizzle(tempImageLocation);

            // DateTime Creation
            var date = DateTime.Now;
            _datetime_long = date.ToString("yyyy-MM-dd,hh-mm-ss");
            _datetime_shrt = date.ToString("hh:mm.ss");

            // Set Tab Header

            tabItem.Header = new ContentControl
                                 {
                                     Content = "Screenshot {" + _datetime_shrt + "}",
                                     ContextMenu = Settings.homeWindow.BaseContextMenu
                                 };

            // Set Image Name
            lblImageName.Text = _datetime_long + ".png";

            // Set Image
            imageScreenshot.Source = _bitmapImage;

            // Should I save the image?
            if (!Settings.XDKAutoSave) return;

            if (!Directory.Exists(Settings.XDKScreenshotPath))
                Directory.CreateDirectory(Settings.XDKScreenshotPath);

            var filePath = Settings.XDKScreenshotPath + "\\" + _datetime_long + ".png";
            SaveImage(filePath);
        }
        /// <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;
        }
Ejemplo n.º 4
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();
            }
        }
Ejemplo n.º 5
0
 // get raw bytes from BitmapImage using BitmapImage.CopyPixels
 private byte[] GetImageByteArray(BitmapSource bi)
 {
     var rawStride = (bi.PixelWidth * bi.Format.BitsPerPixel + 7) / 8;
     var result = new byte[rawStride * bi.PixelHeight];
     bi.CopyPixels(result, rawStride, 0);
     return result;
 }
Ejemplo n.º 6
0
		public WriteableBitmap (BitmapSource source) : base (SafeNativeMethods.writeable_bitmap_new (), true)
		{
			// if source is null then source.native will throw a NRE (like MS SL3 does)
			NativeMethods.writeable_bitmap_initialize_from_bitmap_source (native, source.native);

			// FIXME: we need to test if modifications
			// done to the WB update the BitmapSource's
			// pixel data.  If they do, we can't use this
			// copying code and need to do more
			// complicated tricks to get the pixels array
			// to reflect the contents of the
			// bitmapsource.
			//
			// FIXME: we aren't taking row stride into
			// account here.  we're assuming the pixel
			// data of the source is 32 bits.
			AllocatePixels (source.PixelWidth, source.PixelHeight);

			IntPtr bitmap_data = NativeMethods.bitmap_source_get_bitmap_data (source.native);
			if (bitmap_data != IntPtr.Zero)
				Marshal.Copy (bitmap_data, pixels, 0, pixels.Length);

			PinAndSetBitmapData ();

			Invalidate ();
		}
Ejemplo n.º 7
0
        public override void Dispose()
        {
            _src = null;
            _palette = null;

            base.Dispose();
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
0
 public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource srs)
 {
     System.Drawing.Bitmap temp = null;
     System.Drawing.Bitmap result;
     System.Drawing.Graphics g;
     int width = srs.PixelWidth;
     int height = srs.PixelHeight;
     int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
     byte[] bits = new byte[height * stride];
     srs.CopyPixels(bits, stride, 0);
     unsafe
     {
         fixed (byte* pB = bits)
         {
             IntPtr ptr = new IntPtr(pB);
             temp = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppPArgb, ptr);
         }
     }
     // Copy the image back into a safe structure
     result = new System.Drawing.Bitmap(width, height);
     g = System.Drawing.Graphics.FromImage(result);
     g.DrawImage(temp, 0, 0);
     g.Dispose();
     return result;
 }
Ejemplo n.º 10
0
        /// <summary> 
        /// Construct a ColorConvertedBitmap
        /// </summary>
        /// <param name="source">Input BitmapSource to color convert</param>
        /// <param name="sourceColorContext">Source Color Context</param> 
        /// <param name="destinationColorContext">Destination Color Context</param>
        /// <param name="format">Destination Pixel format</param> 
        public ColorConvertedBitmap(BitmapSource source, ColorContext sourceColorContext, ColorContext destinationColorContext, PixelFormat format) 
            : base(true) // Use base class virtuals
        { 
            if (source == null)
            {
                throw new ArgumentNullException("source");
            } 

            if (sourceColorContext == null) 
            { 
                throw new ArgumentNullException("sourceColorContext");
            } 

            if (destinationColorContext == null)
            {
                throw new ArgumentNullException("destinationColorContext"); 
            }
 
            _bitmapInit.BeginInit(); 

            Source = source; 
            SourceColorContext = sourceColorContext;
            DestinationColorContext = destinationColorContext;
            DestinationFormat = format;
 
            _bitmapInit.EndInit();
            FinalizeCreation(); 
        } 
 public Stream CompressImageToStream(BitmapSource compressSource,int height,int width)
 {
     var writeBmp = new WriteableBitmap(compressSource);
     MemoryStream controlStream = new MemoryStream();
     writeBmp.SaveJpeg(controlStream, width, height, 0, 100);
     return controlStream;
 }
Ejemplo n.º 12
0
        private static unsafe BitmapSource ToGrayScale(BitmapSource source)
        {
            const int PIXEL_SIZE = 4;
            int width = source.PixelWidth;
            int height = source.PixelHeight;
            var bitmap = new WriteableBitmap(source);

            bitmap.Lock();
            var backBuffer = (byte*)bitmap.BackBuffer.ToPointer();
            for (int y = 0; y < height; y++)
            {
                var row = backBuffer + (y * bitmap.BackBufferStride);
                for (int x = 0; x < width; x++)
                {
                    var grayScale = (byte)(((row[x * PIXEL_SIZE + 1]) + (row[x * PIXEL_SIZE + 2]) + (row[x * PIXEL_SIZE + 3])) / 3);
                    for (int i = 0; i < PIXEL_SIZE; i++)
                        row[x * PIXEL_SIZE + i] = grayScale;
                }
            }

            bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
            bitmap.Unlock();

            return bitmap;
        }
Ejemplo n.º 13
0
        public SolverOutput(BitmapSource data, List<Solver.Colorizer> colorpalette, IEnumerable<Charge> charges)
        {
            InitializeComponent();
            _outputdata = data;
            _charges = new List<Charge>(charges);
            gridField.Background = new ImageBrush(data);

            recMapHelper.Fill = Helper.ConvertToBrush(colorpalette);

            foreach (Charge charge in _charges)
            {
                if (charge.IsActive)
                {
                    var newfPoint = new FieldPoint
                                        {
                                            Height = 6,
                                            Width = 6,
                                            HorizontalAlignment = HorizontalAlignment.Left,
                                            VerticalAlignment = VerticalAlignment.Top,
                                            Margin = new Thickness(0, 0, 0, 0),
                                            Mcharge = charge
                                        };
                    var tgroup = new TransformGroup();
                    var tt = new TranslateTransform(charge.Location.X + 14, charge.Location.Y + 14);
                    tgroup.Children.Add(tt);

                    gridField.Children.Add(newfPoint);
                    newfPoint.RenderTransform = tgroup;
                }
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 15
0
        public void Process(object sender, CapturedScreenshotEventArgs image)
        {
            EventHandler<CapturedScreenshotEventArgs> actionWhite = (s, e) =>
            {
                _white = GetScreenshot();

                _effectBackgroundBlack.Process(this, image);
            };

            EventHandler<CapturedScreenshotEventArgs> actionBlack = (s2, e2) =>
            {
                _black = GetScreenshot();

                OnBothFiltered(new CapturedScreenshotEventArgs(null));
            };

            _effectBackground.Filtered += actionWhite;
            _effectBackground.Process(this, image);

            _effectBackgroundBlack = new EffectBackground(_effectBackground.X, _effectBackground.Y, _effectBackground.Width, _effectBackground.Height);
            _effectBackgroundBlack.SetBackground(new SolidColorBrush(Colors.Black));
            _effectBackgroundBlack.Filtered += actionBlack;

            this.BothFiltered += ProcessTransparency;
        }
Ejemplo n.º 16
0
 public IEnumerable<RecognitionResult> RecognizeScaleEachVariation(BitmapSource bitmap, ZoneConfiguration config)
 {
     var bitmaps = BitmapGenerators.SelectMany(g => g.Generate(bitmap));
     var scaled = bitmaps.Select(ScaleIfEnabled);
     var recognitions = scaled.SelectMany(bmp => RecognizeCore(config, bmp));
     return recognitions;
 }
Ejemplo n.º 17
0
        public static System.Drawing.Bitmap BMPFromBitmapSource(BitmapSource source, int iCount)
        {
            //int width = 128;
            //int height = 128;
            //int stride = width;
            //byte[] pixels = new byte[height * stride];

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

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

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

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

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
            return bitmap;
        }
Ejemplo n.º 18
0
        private void ExtractImage(List<WriteableBitmap> tempTiles, BitmapSource image, int spacing, int offset, IProgress<ProgressDialogState> progress = null)
        {
            var sourceImage = BitmapFactory.ConvertToPbgra32Format(image);

            var jump = 16 + spacing;
            var totalTiles = ((image.PixelWidth - offset) / jump) * ((image.PixelHeight - offset) / jump);
            var currentTile = 0;

            for (var y = offset; y < image.PixelHeight; y += jump)
            {
                for (var x = offset; x < image.PixelWidth; x += jump)
                {
                    var tileImage = new WriteableBitmap(16, 16, 96, 96, PixelFormats.Pbgra32, null);
                    tileImage.Blit(new System.Windows.Rect(0, 0, 16, 16), sourceImage, new System.Windows.Rect(x, y, 16, 16));
                    tempTiles.Add(tileImage);

                    currentTile++;
                    if (progress != null)
                    {
                        progress.Report(new ProgressDialogState() {
                            ProgressPercentage = currentTile * 100 / totalTiles,
                            Description = string.Format("Extracting {0} / {1}", currentTile, totalTiles)
                        });
                    }
                }
            }
        }
Ejemplo n.º 19
0
 public static void Save(BitmapSource image, string filename)
 {
     PngBitmapEncoder encoder = new PngBitmapEncoder();
     encoder.Frames.Add(BitmapFrame.Create(image));
     using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
         encoder.Save(stream);
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Construct a TransformedBitmap with the given newTransform
        /// </summary>
        /// <param name="source">BitmapSource to apply to the newTransform to</param>
        /// <param name="newTransform">Transform to apply to the bitmap</param>
        public TransformedBitmap(BitmapSource source, Transform newTransform)
            : base(true) // Use base class virtuals
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (newTransform == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.Image_NoArgument, "Transform"));
            }

            if (!CheckTransform(newTransform))
            {
                throw new InvalidOperationException(SR.Get(SRID.Image_OnlyOrthogonal));
            }

            _bitmapInit.BeginInit();

            Source = source;
            Transform = newTransform;

            _bitmapInit.EndInit();
            FinalizeCreation();
        }
Ejemplo n.º 21
0
        private static void SaveBitmap(BitmapSource bitmap, string destination)
        {
            BitmapEncoder encoder;

            switch (Path.GetExtension(destination).ToUpperInvariant())
            {
                case ".BMP":
                    encoder = new BmpBitmapEncoder();
                    break;

                case ".GIF":
                    encoder = new GifBitmapEncoder();
                    break;

                case ".JPG":
                    encoder = new JpegBitmapEncoder() { QualityLevel = 100 };
                    break;

                case ".PNG":
                    encoder = new PngBitmapEncoder();
                    break;

                case ".TIF":
                    encoder = new TiffBitmapEncoder() { Compression = TiffCompressOption.Zip };
                    break;

                default:
                    throw new NotSupportedException("Not supported output extension.");
            }

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(new FileStream(destination, FileMode.Create));
        }
 static UnifiedModelSystemInterface()
 {
     try
     {
         try
         {
             ModuleIcon = CreateBitmapCache("pack://application:,,,/XTMF.Gui;component/Resources/Settings.png");
             ModuleIcon.Freeze();
             ListIcon = CreateBitmapCache("pack://application:,,,/XTMF.Gui;component/Resources/Plus.png");
             ListIcon.Freeze();
         }
         catch
         {
         }
         HighlightColour = (Color)Application.Current.TryFindResource("SelectionBlue");
         FocusColour = (Color)Application.Current.TryFindResource("FocusColour");
         ControlBackgroundColour = (Color)Application.Current.TryFindResource("ControlBackgroundColour");
         AddingYellow = (Color)Application.Current.TryFindResource("AddingYellow");
         InformationGreen = (Color)Application.Current.TryFindResource("InformationGreen");
         WarningRed = (Color)Application.Current.TryFindResource("WarningRed");
     }
     catch
     {
     }
 }
Ejemplo n.º 23
0
        public ImageReceivedEventArgs(BitmapSource image)
        {
            if (image == null)
                throw new ArgumentNullException("image");

            this.image = image;
        }
Ejemplo n.º 24
0
        public static void SaveBitmapSource2File(string filename, BitmapSource image5)
        {
            try
            {
                if (filename == null)
                {
                    _logger.Warn("SaveBitmapSource2File: filename is null");
                    return;
                }
                if (image5 == null)
                {
                    _logger.Error(string.Format("Survey UI: Trying to saved a null image source from file {0}", filename));
                    return;
                }

                if (filename != string.Empty)
                {
                    using (FileStream stream5 = new FileStream(filename, FileMode.Create))
                    {
                        PngBitmapEncoder encoder5 = new PngBitmapEncoder();
                        encoder5.Frames.Add(BitmapFrame.Create(image5));
                        encoder5.Save(stream5);
                        stream5.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("SaveBitmapSource2File", ex);
            }
        }
Ejemplo n.º 25
0
 public static BitmapSource LoadBitmap(System.Drawing.Bitmap source)
 {
     handle = source.GetHbitmap();
     bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
     DeleteObject(handle);
     return bitmapSource;
 }
Ejemplo n.º 26
0
        private string ExtractBestTextCandidate(BitmapSource bitmap, ITextualDataFilter filter, Symbology symbology)
        {
            var page = Engine.Recognize(bitmap, RecognitionConfiguration.FromSingleImage(bitmap, filter, symbology));
            var zone = page.RecognizedZones.First();

            return zone.RecognitionResult.Text;
        }
Ejemplo n.º 27
0
 public WriteableBitmap(
     BitmapSource source
     )
     : base(true) // Use base class virtuals
 {
     InitFromBitmapSource(source);
 }
Ejemplo n.º 28
0
        public static BitmapSource CreateThemedBitmapSource(BitmapSource src, Color bgColor, bool isHighContrast)
        {
            unchecked {
                if (src.Format != PixelFormats.Bgra32)
                    src = new FormatConvertedBitmap(src, PixelFormats.Bgra32, null, 0.0);
                var pixels = new byte[src.PixelWidth * src.PixelHeight * 4];
                src.CopyPixels(pixels, src.PixelWidth * 4, 0);

                var bg = HslColor.FromColor(bgColor);
                int offs = 0;
                while (offs + 4 <= pixels.Length) {
                    var hslColor = HslColor.FromColor(Color.FromRgb(pixels[offs + 2], pixels[offs + 1], pixels[offs]));
                    double hue = hslColor.Hue;
                    double saturation = hslColor.Saturation;
                    double luminosity = hslColor.Luminosity;
                    double n1 = Math.Abs(0.96470588235294119 - luminosity);
                    double n2 = Math.Max(0.0, 1.0 - saturation * 4.0) * Math.Max(0.0, 1.0 - n1 * 4.0);
                    double n3 = Math.Max(0.0, 1.0 - saturation * 4.0);
                    luminosity = TransformLuminosity(hue, saturation, luminosity, bg.Luminosity);
                    hue = hue * (1.0 - n3) + bg.Hue * n3;
                    saturation = saturation * (1.0 - n2) + bg.Saturation * n2;
                    if (isHighContrast)
                        luminosity = ((luminosity <= 0.3) ? 0.0 : ((luminosity >= 0.7) ? 1.0 : ((luminosity - 0.3) / 0.4))) * (1.0 - saturation) + luminosity * saturation;
                    var color = new HslColor(hue, saturation, luminosity, 1.0).ToColor();
                    pixels[offs + 2] = color.R;
                    pixels[offs + 1] = color.G;
                    pixels[offs] = color.B;
                    offs += 4;
                }

                BitmapSource newImage = BitmapSource.Create(src.PixelWidth, src.PixelHeight, src.DpiX, src.DpiY, PixelFormats.Bgra32, src.Palette, pixels, src.PixelWidth * 4);
                newImage.Freeze();
                return newImage;
            }
        }
Ejemplo n.º 29
0
 public BitmapSource Apply(BitmapSource image)
 {
     var grayScale = ToGrayScale(image);
     var filter = new Threshold(factor);
     var bmp = filter.Apply(grayScale);
     return bmp.ToBitmapImage();
 }
Ejemplo n.º 30
0
        public HaloScreenshot(string tempImageLocation, LayoutDocument tabItem)
        {
            InitializeComponent();

            // Convert DDS to BitmapImage
            _bitmapImage = DDSConversion.Deswizzle(tempImageLocation);

            // DateTime Creation
            DateTime date = DateTime.Now;
            _datetime_long = date.ToString("yyyy-MM-dd,hh-mm-ss");
            _datetime_shrt = date.ToString("hh:mm.ss");

            // Set Tab Header
            tabItem.Title = "Screenshot {" + _datetime_shrt + "}";

            // Set Image Name
            lblImageName.Text = _datetime_long + ".png";

            // Set Image
            imageScreenshot.Source = _bitmapImage;

            // Should I save the image?
            if (!App.AssemblyStorage.AssemblySettings.XdkAutoSave) return;

            if (!Directory.Exists(App.AssemblyStorage.AssemblySettings.XdkScreenshotPath))
                Directory.CreateDirectory(App.AssemblyStorage.AssemblySettings.XdkScreenshotPath);

            string filePath = App.AssemblyStorage.AssemblySettings.XdkScreenshotPath + "\\" + _datetime_long + ".png";
            SaveImage(filePath);
        }
Ejemplo n.º 31
0
        protected internal static BitmapSource GetBitmapSource(StockIconIdentifier identifier, StockIconOptions flags)
        {
            BitmapSource bitmapSource = (BitmapSource)InteropHelper.MakeImage(identifier, StockIconOptions.Handle | flags);

            if (bitmapSource != null)
            {
                bitmapSource.Freeze();
            }

            return(bitmapSource);
        }
 public BitmapSource convertToBitmapSource(string imageFileResourceName)
 {
     System.Drawing.Bitmap picture = (System.Drawing.Bitmap)Properties.Resources.ResourceManager.GetObject(imageFileResourceName);
     // Problem - the image is returned as a bitmap, but the
     // source property of the image box requires a 'BitmapSource'.
     // Converting Bitmap to BitmapSource here.
     System.Windows.Media.Imaging.BitmapSource sourcePicture =
         CustomExtensions.BitmapSourceExtension.ToBitmapSource(picture);
     //pass the source back from the function, do a return
     return(sourcePicture);
 }
Ejemplo n.º 33
0
        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());
        }
Ejemplo n.º 34
0
        private void setBackground()
        {
            ImageSourceConverter c = new ImageSourceConverter();
            Bitmap bitmap          = backgrounds[position];

            System.Windows.Media.Imaging.BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                bitmap.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty,
                BitmapSizeOptions.FromWidthAndHeight(bitmap.Width, bitmap.Height)
                );

            Backdrop.Source = b;
        }
        public async Task ListenAsync()
        {
            while (this.run)
            {
                try
                {
                    var context = await this.listener.GetContextAsync();

                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;


                    // Get Frame Buffer
                    System.Windows.Media.Imaging.BitmapSource bitmapsource = this.cam.video.Frame_GetCurrent();
                    MemoryStream  outStream = new MemoryStream();
                    BitmapEncoder enc       = new BmpBitmapEncoder();
                    enc.Frames.Add(BitmapFrame.Create(bitmapsource));
                    enc.Save(outStream);
                    byte[] frame = outStream.GetBuffer();


                    // Send Frames
                    response.StatusCode      = 200;
                    response.ContentLength64 = frame.Length;
                    response.ContentType     = "image/jpeg";
                    response.KeepAlive       = true;
                    response.Headers.Add("Refresh", "0");
                    response.OutputStream.Write(frame, 0, frame.Length);
                    response.OutputStream.Close();



                    /*
                     * // Create Buffer With HTML
                     * string responseString = "<HTML><HEAD><meta http-equiv='refresh' content='0'" +
                     *  "></HEAD><BODY>" +
                     *  "Hello World" +
                     *  "</BODY></HTML>";
                     * byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                     * // Send Buffer
                     * response.ContentLength64 = buffer.Length;
                     * response.OutputStream.Write(buffer, 0, buffer.Length);
                     * response.OutputStream.Close();
                     */

                    //enc.Frames.Clear();
                    //response.Headers.Clear();
                } catch (Exception ex)
                {
                    Console.WriteLine($"Source:{ex.Source}\nStackTrace:{ex.StackTrace}\n{ex.Message}");
                }
            }
        }
Ejemplo n.º 36
0
        private void ShowPreviewImage(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data);

            System.Windows.Media.Imaging.BitmapSource bitmapSource =
                System.Windows.Media.Imaging.BitmapFrame.Create(
                    ms,
                    System.Windows.Media.Imaging.BitmapCreateOptions.None,
                    System.Windows.Media.Imaging.BitmapCacheOption.OnLoad
                    );
            this.PreviewImage.Source = bitmapSource;
        }
Ejemplo n.º 37
0
        public static System.Drawing.Bitmap GetWinformBitmap(System.Windows.Media.Imaging.BitmapSource srcBitmap)
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                PngBitmapEncoder enc = new PngBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(srcBitmap));
                enc.Save(outStream);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);

                return(new Bitmap(bitmap));
            }
        }
Ejemplo n.º 38
0
        public static Bitmap ToWinFormsBitmap(this System.Windows.Media.Imaging.BitmapSource bitmapsource)
        {
            using (MemoryStream stream = new MemoryStream()) {
                System.Windows.Media.Imaging.BitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder();
                enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapsource));
                enc.Save(stream);

                using (Bitmap tempBitmap = new Bitmap(stream)) {
                    return(new Bitmap(tempBitmap));
                }
            }
        }
        //move this whole thing up to another ViewMode called "ImageViewerMultiPageViewMode"
        public void SwitchToPage(int pageIndex)
        {
            if (pageIndex >= 0 && m_ImageViewerPages != null && m_ImageViewerPages.Count > 0 && m_ImageViewerPages.ContainsKey(pageIndex) && m_ImageViewerPages[pageIndex] != null)
            {
                if (m_ImageViewerViewModels.ContainsKey(pageIndex) && m_ImageViewerViewModels[pageIndex] != null)
                {
                    m_ImageViewerViewModel = m_ImageViewerViewModels[pageIndex];
                }
                else
                {
                    System.Windows.Media.Imaging.BitmapSource bitmapSource = UserControls.ImageResourceModerator.Instance.GetBitmapSource(m_FileName, pageIndex);

                    m_ImageViewerViewModel = new ImageViewerViewModel(bitmapSource, m_ImageViewerPages[pageIndex].Rotation, m_ImageViewerPages[pageIndex].Skew.X, m_ImageViewerPages[pageIndex].Skew.Y, m_ImageViewerPages[pageIndex].Shift, m_FileName, pageIndex);
                    m_ImageViewerViewModel.FirstPageIndex = m_FirstPageIndex;
                    m_ImageViewerViewModel.LastPageIndex  = m_LastPageIndex;

                    m_ImageViewerViewModel.DisableMaskAutoDrawRois();

                    m_ImageViewerViewModel.Rois.Clear();
                    m_ImageViewerPages[pageIndex].Rois.ToList().ForEach(x => m_ImageViewerViewModel.Rois.Add(x));
                    CopyFormat(m_ImageViewerPages[pageIndex].Rois, m_ImageViewerViewModel.Rois);

                    m_ImageViewerViewModel.RecognitionRois.Clear();
                    m_ImageViewerPages[pageIndex].RecognitionRois.ToList().ForEach(x => m_ImageViewerViewModel.RecognitionRois.Add(x));
                    CopyFormat(m_RecognitionRois, m_ImageViewerViewModel.RecognitionRois);

                    m_ImageViewerViewModel.GoldenRois.Clear();
                    m_ImageViewerPages[pageIndex].GoldenRois.ToList().ForEach(x => m_ImageViewerViewModel.GoldenRois.Add(x));
                    CopyFormat(m_GoldenRois, m_ImageViewerViewModel.GoldenRois);

                    m_ImageViewerViewModel.SelectedRois.Clear();
                    m_ImageViewerPages[pageIndex].SelectedRois.ToList().ForEach(x => m_ImageViewerViewModel.SelectedRois.Add(x));
                    CopyFormat(m_SelectedRois, m_ImageViewerViewModel.SelectedRois);

                    m_ImageViewerViewModel.SelectedRoisSubGroup1.Clear();
                    m_ImageViewerPages[pageIndex].SelectedRoisSubGroup1.ToList().ForEach(x => m_ImageViewerViewModel.SelectedRoisSubGroup1.Add(x));
                    CopyFormat(m_SelectedRoisSubGroup1, m_ImageViewerViewModel.SelectedRoisSubGroup1);

                    m_ImageViewerViewModel.SelectedRoisSubGroup2.Clear();
                    m_ImageViewerPages[pageIndex].SelectedRoisSubGroup2.ToList().ForEach(x => m_ImageViewerViewModel.SelectedRoisSubGroup2.Add(x));
                    CopyFormat(m_SelectedRoisSubGroup2, m_ImageViewerViewModel.SelectedRoisSubGroup2);

                    m_ImageViewerViewModel.EnableMaskAutoDrawRois();
                    m_ImageViewerViewModels.Add(pageIndex, m_ImageViewerViewModel); //for next time
                }

                UserControls.ImageResourceModerator.Instance.SignalToProcessFrames(m_FileName, pageIndex, m_ImageViewerViewModels[pageIndex].InstanceID);

                OnPropertyChanged("ImageViewerViewModel");
            }
        }
Ejemplo n.º 40
0
        public static BitmapSource GetBitmapSource(System.Drawing.Bitmap bmp)
        {
            IntPtr hBitmap = bmp.GetHbitmap();

            System.Windows.Media.Imaging.BitmapSource bs =
                System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    hBitmap,
                    IntPtr.Zero,
                    System.Windows.Int32Rect.Empty,
                    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            DeleteObject(hBitmap);

            return(bs);
        }
Ejemplo n.º 41
0
        public System.Windows.Media.Imaging.BitmapSource CreateBarCodeBitmapSource(string txt, int scale)
        {
            string result = DoBarCode(txt, scale);

            IntPtr hBitmap = newBitmap.GetHbitmap();

            System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

            return(bitmapSource);
        }
Ejemplo n.º 42
0
        public swmi.BitmapFrame Get(swmi.BitmapSource image, float scale, int width, int height, swm.BitmapScalingMode scalingMode)
        {
            if (width <= 0 || height <= 0 || scale <= 0)
            {
                return(null);
            }

            var _cachedFrame = _cachedFrameReference?.Target as swmi.BitmapFrame;

            // if parameters are the same, return cached bitmap
            if (_cachedFrame != null && scale == _scale && width == _width && height == _height && scalingMode == _scalingMode)
            {
                return(_cachedFrame);
            }

            // generate a new bitmap with the desired size & scale.
            var scaledwidth  = (int)Math.Round(width * scale);
            var scaledheight = (int)Math.Round(height * scale);

            if (scaledwidth <= 0 || scaledheight <= 0)
            {
                return(null);
            }
            var group = new swm.DrawingGroup();

            swm.RenderOptions.SetBitmapScalingMode(group, scalingMode);
            group.Children.Add(new swm.ImageDrawing(image, new sw.Rect(0, 0, width, height)));

            var targetVisual = new swm.DrawingVisual();

            using (var targetContext = targetVisual.RenderOpen())
                targetContext.DrawDrawing(group);

            // note, this uses a GDI handle, which are limited (only 5000 or so can be created).
            // There's no way to get around it other than just not creating that many and using GC.Collect/WaitForPendingFinalizers.
            // we can't do it in Eto as it'd be a serious performance hit.
            var target = new swmi.RenderTargetBitmap(scaledwidth, scaledheight, 96 * scale, 96 * scale, swm.PixelFormats.Default);

            target.Render(targetVisual);
            target.Freeze();

            _cachedFrame = swmi.BitmapFrame.Create(target);
            _cachedFrame.Freeze();
            _scale                = scale;
            _width                = width;
            _height               = height;
            _scalingMode          = scalingMode;
            _cachedFrameReference = new WeakReference(_cachedFrame);
            return(_cachedFrame);
        }
Ejemplo n.º 43
0
        public static Sd.Bitmap ToBitmap(this Si.BitmapSource input)
        {
            Sd.Bitmap output = new Sd.Bitmap(10, 10);
            using (MemoryStream outStream = new MemoryStream())
            {
                Si.PngBitmapEncoder enc = new Si.PngBitmapEncoder();

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

            return(output);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Bitmap => BitmapSource (Image.Source = ...)
        /// </summary>
        private System.Windows.Media.Imaging.BitmapSource GetBitmapSource(System.Drawing.Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();

            System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()
                );

            // Free the memory used by the GDI bitmap object (GDI does not release this).
            DeleteObject(hBitmap);
            return(bitmapSource);
        }
Ejemplo n.º 45
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return(null);
            }

            System.IO.MemoryStream ms     = new System.IO.MemoryStream(((System.Data.Linq.Binary)value).ToArray());
            System.Drawing.Bitmap  bitmap = new System.Drawing.Bitmap(ms);
            System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                bitmap.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            return(bitmapSource);
        }
Ejemplo n.º 46
0
        public void SaveImage(string filename, Array bmpData, int width, int height, System.Windows.Media.PixelFormat format, double dpi = 96)
        {
            int stride = ((width * format.BitsPerPixel) / 8);

            System.Windows.Media.Imaging.BitmapSource bs = System.Windows.Media.Imaging.BitmapSource.Create(
                width,
                height,
                dpi,
                dpi,
                format,
                null,
                bmpData,
                stride);

            // file extention
            var ext = System.IO.Path.GetExtension(filename).ToLower();

            BitmapEncoder encoder;

            switch (ext)
            {
            case ".bmp":
                encoder = new BmpBitmapEncoder();
                break;

            case ".tif":
                encoder = new TiffBitmapEncoder {
                    Compression = TiffCompressOption.None
                };
                break;

            case ".png":
                encoder = new PngBitmapEncoder();
                break;

            default:
                encoder = null;
                break;
            }

            using (Stream stream = new FileStream(filename, FileMode.Create))
            {
                var bf = BitmapFrame.Create(bs);
                encoder.Frames.Add(bf);
                encoder.Save(stream);
            }
        }
Ejemplo n.º 47
0
        static swmi.BitmapFrame Resize(swmi.BitmapSource image, float scale, int width, int height, swm.BitmapScalingMode scalingMode)
        {
            var group = new swm.DrawingGroup();

            swm.RenderOptions.SetBitmapScalingMode(group, scalingMode);
            group.Children.Add(new swm.ImageDrawing(image, new sw.Rect(0, 0, width, height)));
            var targetVisual  = new swm.DrawingVisual();
            var targetContext = targetVisual.RenderOpen();

            targetContext.DrawDrawing(group);
            width  = (int)Math.Round(width * scale);
            height = (int)Math.Round(height * scale);
            var target = new swmi.RenderTargetBitmap(width, height, 96 * scale, 96 * scale, swm.PixelFormats.Default);

            targetContext.Close();
            target.Render(targetVisual);
            return(swmi.BitmapFrame.Create(target));
        }
Ejemplo n.º 48
0
        public InformacionUsuario(MainWindow mPrincipal)
        {
            InitializeComponent();
            menuPrincipal = mPrincipal;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Properties.Settings.Default.idioma);
            AplicarIdioma();
            AplicarEstilo();

            if (Properties.Settings.Default.tamanoLetra == "P")
            {
                AplicarTamanoLetra(-3);
            }
            else if (Properties.Settings.Default.tamanoLetra == "G")
            {
                AplicarTamanoLetra(3);
            }
            else
            {
                AplicarTamanoLetra(0);
            }


            String textExport = "1111" + "[N]" + Properties.Settings.Default.nombre + "[N]" +
                                "[A]" + Properties.Settings.Default.apellidos + "[A]" +
                                "[AN]" + Properties.Settings.Default.añoNacimiento + "[AN]" +
                                "[P]" + Properties.Settings.Default.peso + "[P]" +
                                "[PRA]" + Properties.Settings.Default.pruebaReflejosAciertos + "[PRA]" +
                                "[PRF]" + Properties.Settings.Default.pruebaReflejosFallos + "[PRF]" +
                                "[D]" + Properties.Settings.Default.Daltonico + "[D]" +
                                "[M]" + Properties.Settings.Default.tipoMovilidad + "[M]";
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode    qrCode    = new QrCode();

            qrEncoder.TryEncode(textExport, out qrCode);
            GraphicsRenderer renderer = new GraphicsRenderer(new FixedCodeSize(400, QuietZoneModules.Zero), System.Drawing.Brushes.Black, System.Drawing.Brushes.White);
            MemoryStream     ms       = new MemoryStream();

            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
            var imageTemporal = new Bitmap(ms);
            var image         = new Bitmap(imageTemporal, new System.Drawing.Size(new System.Drawing.Point(200, 200)));

            System.Windows.Media.Imaging.BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(image.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(image.Width, image.Height));
            codigoQR.Source = b;
        }
        public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource)
        {
            //convert image format
            var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();

            src.BeginInit();
            src.Source            = bitmapsource;
            src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
            src.EndInit();

            //copy to bitmap
            Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var    data   = bitmap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bitmap.UnlockBits(data);

            return(bitmap);
        }
Ejemplo n.º 50
0
        public MainWindow()
        {
            InitializeComponent();
            image  = new System.Windows.Controls.Image();
            bimage = new Bitmap(@"C:\Users\Nazar\Documents\Visual Studio 2015\Projects\RiverMaker\height2smallmod.PNG");
            cnt    = new GridStorageController(25, bimage);
            cnt.LinkPoints();
            cnt.storage.DefineWaterIncome();
            //cnt.GetB(3000, bimage.Width, bimage.Height + 100);
            //var points = cnt.BuildStorage(200, bimage);
            //image = new System.Windows.Controls.Image();
            System.Windows.Media.Imaging.BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                bimage.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty,
                BitmapSizeOptions.FromWidthAndHeight(bimage.Width, bimage.Height));
            image.Source  = b;
            image.Stretch = Stretch.UniformToFill;
            //canvas.Children.Add(image);

            longestRiver = new Polyline();
        }
        static byte[] GetBytesFromBitmapSource(System.Windows.Media.Imaging.BitmapSource bmp)
        {
            if (bmp == null)
            {
                return(null);
            }

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

                return(bit);
            }
        }
Ejemplo n.º 52
0
        public TreeViewItemExecutable(string name, string path) : base(name, path)
        {
            this.Category = TreeViewCategory.Executable;
            try
            {
                System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
                Bitmap bitmap           = ico.ToBitmap();

                System.Windows.Media.Imaging.BitmapSource bitmapSource =
                    System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        bitmap.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()
                        );

                this.Icon = bitmapSource;
            }
            catch (Exception) { }
        }
Ejemplo n.º 53
0
        private BitmapImage DisplayGrayImage()
        {
            BitmapImage bitmapimage = new BitmapImage();

            bitmapimage.BeginInit();
            bitmapimage.UriSource = new Uri(@_mfolderPath + "\\" + "OProcessedImg.png", UriKind.Absolute);
            bitmapimage.EndInit();

            return(bitmapimage);

            //BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap
            //(
            //    _mconvgrayimg.GetHbitmap(),
            //    IntPtr.Zero,
            //    Int32Rect.Empty,
            //    BitmapSizeOptions.FromEmptyOptions()
            //);
            //return bitmapSource;
            System.Windows.Media.Imaging.BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(_mconvgrayimg.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(_mconvgrayimg.Width, _mconvgrayimg.Height));
            //return b;
        }
Ejemplo n.º 54
0
        private void Button1_Click(object sender, RoutedEventArgs e)  // загружаем файл
        {
            OpenFileDialog OFD = new OpenFileDialog();

            OFD.Filter = "Images (*.jpg)|*.jpg";
            bool?result = OFD.ShowDialog();

            if (result == true)
            {
                picture = new Bitmap(Bitmap.FromFile(OFD.FileName));
            }


            System.Windows.Media.Imaging.BitmapSource b =
                System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    picture.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
            Image1.Source = b;
        }
Ejemplo n.º 55
0
        public byte[] EncodeWpf(SWMI.BitmapSource image, float bitrate = WsqCodec.Constants.DefaultBitrate, bool autoConvertToGrayscale = true)
        {
            if (image == null)
            {
                throw new ArgumentNullException("image");
            }

            SWMI.BitmapSource source = null;
            if (autoConvertToGrayscale)
            {
                source = Conversions.ToGray8BitmapSource(image);
            }
            else
            {
                source = image;
            }

            var data = Conversions.WpfImageToImageInfo(source);

            return(WsqCodec.Encode(data, bitrate, Comment));
        }
Ejemplo n.º 56
0
        public static void SaveGray16(string path, int width, int height, UInt16[] data)
        {
            int stride = width * 2; // ピクセル当たり2Byte

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

            stream.Close();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="bitmap">変換元の画像(Bitmap型)</param>
        /// <returns></returns>
        private ImageSource convertBitmapToImageSource(Bitmap bitmap)
        {
            // MemoryStreamを利用した変換処理
            using (var ms = new System.IO.MemoryStream())
            {
                // MemoryStreamに書き出す
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                // MemoryStreamをシーク
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                // MemoryStreamからBitmapFrameを作成
                // (BitmapFrameはBitmapSourceを継承しているのでそのまま渡せばOK)
                System.Windows.Media.Imaging.BitmapSource bitmapSource =
                    System.Windows.Media.Imaging.BitmapFrame.Create(
                        ms,
                        System.Windows.Media.Imaging.BitmapCreateOptions.None,
                        System.Windows.Media.Imaging.BitmapCacheOption.OnLoad
                        );

                return(bitmapSource);
            }
        }
Ejemplo n.º 58
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(@"C:\Hits\Hits\Views\Images\blankUser.png");
                System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bitmap.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                return(bitmapSource);
            }

            System.Windows.Media.Imaging.BitmapImage biImg = new System.Windows.Media.Imaging.BitmapImage();
            MemoryStream ms = new MemoryStream((byte[])value);

            biImg.BeginInit();
            biImg.StreamSource = ms;
            biImg.EndInit();

            return(biImg as ImageSource);
        }
Ejemplo n.º 59
0
        public static System.Drawing.Bitmap BitmapSourceToBitmap(System.Windows.Media.Imaging.BitmapSource srs)
        {
            System.Drawing.Bitmap btm = null;
            int width  = srs.PixelWidth;
            int height = srs.PixelHeight;
            int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);

            byte[] bits = new byte[height * stride];

            srs.CopyPixels(bits, stride, 0);

            unsafe
            {
                fixed(byte *pB = bits)
                {
                    IntPtr ptr = new IntPtr(pB);

                    btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppPArgb, ptr);
                }
            }
            return(btm);
        }
Ejemplo n.º 60
0
        public Bitmap Clone(Rectangle?rectangle = null)
        {
            swmi.BitmapSource clone = null;
            ApplicationHandler.InvokeIfNecessary(() =>
            {
                if (rectangle != null)
                {
                    var rect = rectangle.Value;
                    var data = new byte[Stride * Control.PixelHeight];
                    Control.CopyPixels(data, Stride, 0);
                    var target = new swmi.WriteableBitmap(rect.Width, rect.Height, Control.DpiX, Control.DpiY, Control.Format, null);
                    target.WritePixels(rect.ToWpfInt32(), data, Stride, destinationX: 0, destinationY: 0);
                    clone = target;
                }
                else
                {
                    clone = Control.Clone();
                }
            });

            return(new Bitmap(Generator, new BitmapHandler(clone)));
        }