Example #1
0
        /// <summary>
        /// Creates a System.Drawing.Bitmap image from a WPF source.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static Bitmap MakeBitmapFromWPF(System.Windows.Media.Imaging.BitmapSource source)
        {
            var    mm  = new MemPtr();
            Bitmap bmp = null;

            if (System.Windows.Application.Current is object)
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    mm.Alloc(bmp.Width * bmp.Height * 4);
                    var bm    = new System.Drawing.Imaging.BitmapData();
                    bm.Scan0  = mm.Handle;
                    bm.Stride = bmp.Width * 4;
                    bm        = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite | System.Drawing.Imaging.ImageLockMode.UserInputBuffer, System.Drawing.Imaging.PixelFormat.Format32bppArgb, bm);
                    source.CopyPixels(System.Windows.Int32Rect.Empty, mm.Handle, (int)mm.Length, bmp.Width * 4);
                    bmp.UnlockBits(bm);
                    mm.Free();
                });
            }
            else
            {
                bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                mm.Alloc(bmp.Width * bmp.Height * 4);
                var bm = new System.Drawing.Imaging.BitmapData();
                bm.Scan0  = mm.Handle;
                bm.Stride = bmp.Width * 4;
                bm        = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite | System.Drawing.Imaging.ImageLockMode.UserInputBuffer, System.Drawing.Imaging.PixelFormat.Format32bppArgb, bm);
                source.CopyPixels(System.Windows.Int32Rect.Empty, mm.Handle, (int)mm.Length, bmp.Width * 4);
                bmp.UnlockBits(bm);
                mm.Free();
            }

            return(bmp);
        }
Example #2
0
        /// <summary>
        /// Returns an average color from a presented Bitmap
        /// </summary>
        /// <param name="bitmap">The bitmap to be evaluated</param>
        /// <returns>An average color from the bitmap</returns>
        public static Color GetAverageColor(System.Windows.Media.Imaging.BitmapSource bitmap)
        {
            var format = bitmap.Format;

            if (format != System.Windows.Media.PixelFormats.Bgr24 &&
                format != System.Windows.Media.PixelFormats.Bgr32 &&
                format != System.Windows.Media.PixelFormats.Bgra32 &&
                format != System.Windows.Media.PixelFormats.Pbgra32)
            {
                throw new InvalidOperationException("BitmapSource must have Bgr24, Bgr32, Bgra32 or Pbgra32 format");
            }

            var width         = bitmap.PixelWidth;
            var height        = bitmap.PixelHeight;
            var numPixels     = width * height;
            var bytesPerPixel = format.BitsPerPixel / 8;
            var pixelBuffer   = new byte[numPixels * bytesPerPixel];

            bitmap.CopyPixels(pixelBuffer, width * bytesPerPixel, 0);

            long blue  = 0;
            long green = 0;
            long red   = 0;

            for (int i = 0; i < pixelBuffer.Length; i += bytesPerPixel)
            {
                blue  += pixelBuffer[i];
                green += pixelBuffer[i + 1];
                red   += pixelBuffer[i + 2];
            }

            return(Color.FromArgb((byte)(red / numPixels), (byte)(green / numPixels), (byte)(blue / numPixels)));
        }
Example #3
0
        /// <summary>
        /// Converts a Wpf <see cref="System.Windows.Media.Imaging.BitmapSource"/> to a Gdi <see cref="System.Drawing.Bitmap"/>.
        /// Note that this works only with 32 bits BRGA bitmaps.
        /// </summary>
        /// <param name="wpfBitmapSource">The Wpf bitmap source.</param>
        /// <returns>The Gdi bitmap.</returns>
        public static System.Drawing.Bitmap ToGdi(System.Windows.Media.Imaging.BitmapSource wpfBitmapSource)
        {
            if (null == wpfBitmapSource)
            {
                throw new ArgumentNullException(nameof(wpfBitmapSource));
            }

            var gdiBitmap = new System.Drawing.Bitmap(
                wpfBitmapSource.PixelWidth,
                wpfBitmapSource.PixelHeight,
                System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            var bitmapData = gdiBitmap.LockBits(
                new System.Drawing.Rectangle(System.Drawing.Point.Empty, gdiBitmap.Size),
                System.Drawing.Imaging.ImageLockMode.WriteOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

            wpfBitmapSource.CopyPixels(
                Int32Rect.Empty,
                bitmapData.Scan0,
                bitmapData.Height * bitmapData.Stride,
                bitmapData.Stride);

            gdiBitmap.UnlockBits(bitmapData);

            return(gdiBitmap);
        }
Example #4
0
        public static MemoryBitmap ToMemoryBitmap(WIC_READABLE src)
        {
            var binfo = src.GetBitmapInfo();

            var dst = new MemoryBitmap(binfo);

            src.CopyPixels(dst.ToByteArray(), binfo.StepByteSize, 0);

            return(dst);
        }
Example #5
0
 public static Emgu.CV.Mat BitmapSourceToEmguCvMat(System.Windows.Media.Imaging.BitmapSource source)
 {
     if (source.Format == PixelFormats.Bgra32)
     {
         Emgu.CV.Mat result = new Emgu.CV.Mat();
         result.Create(source.PixelHeight, source.PixelWidth, Emgu.CV.CvEnum.DepthType.Cv8U, 4);
         source.CopyPixels(Int32Rect.Empty, result.DataPointer, result.Step * result.Rows, result.Step);
         return(result);
     }
     else if (source.Format == PixelFormats.Bgr24)
     {
         Emgu.CV.Mat result = new Emgu.CV.Mat();
         result.Create(source.PixelHeight, source.PixelWidth, Emgu.CV.CvEnum.DepthType.Cv8U, 3);
         source.CopyPixels(Int32Rect.Empty, result.DataPointer, result.Step * result.Rows, result.Step);
         return(result);
     }
     else
     {
         throw new Exception(String.Format("Convertion from BitmapSource of format {0} is not supported.", source.Format));
     }
 }
Example #6
0
        internal static Bitmap GetBitmap(System.Windows.Media.Imaging.BitmapSource source)
        {
            Bitmap bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

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

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

            bmp.UnlockBits(data);

            return(bmp);
        }
Example #7
0
        private Bitmap getBitmapFromSource(System.Windows.Media.Imaging.BitmapSource source)
        {
            Bitmap     bmp  = new Bitmap(source.PixelWidth, source.PixelHeight, PixelFormat.Format32bppPArgb);
            BitmapData data = bmp.LockBits(
                new Rectangle(System.Drawing.Point.Empty, bmp.Size),
                ImageLockMode.WriteOnly,
                PixelFormat.Format32bppPArgb);

            source.CopyPixels(
                Int32Rect.Empty,
                data.Scan0,
                data.Height * data.Stride,
                data.Stride);
            bmp.UnlockBits(data);
            return(bmp);
        }
Example #8
0
        /// <summary>
        /// Creates a GDI bitmap from a WPF bitmap.
        /// </summary>
        /// <param name="img">WPF bitmap source.</param>
        /// <param name="ignoreAlpha">True = creates a bitmap without alpha.</param>
        /// <returns>GDI bitmap.</returns>
        public static Bitmap CreateBitmap(System.Windows.Media.Imaging.BitmapSource img, bool ignoreAlpha)
        {
            var    rect = new Rectangle(0, 0, img.PixelWidth, img.PixelHeight);
            Bitmap bmp  = new Bitmap(img.PixelWidth, img.PixelHeight, ignoreAlpha ? PixelFormat.Format32bppRgb : PixelFormat.Format32bppArgb);

            BitmapData data;

            if (ignoreAlpha)
            {
                data = bmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
            }
            else
            {
                data = bmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            }

            img.CopyPixels(new System.Windows.Int32Rect(0, 0, img.PixelWidth, img.PixelHeight), data.Scan0, 4 * img.PixelWidth * img.PixelHeight, 4 * img.PixelWidth);
            bmp.UnlockBits(data);

            return(bmp);
        }
        /// <remarks>
        /// Stolen and adapted from
        /// <seealso href="http://stackoverflow.com/questions/2284353/is-there-a-good-way-to-convert-between-bitmapsource-and-bitmap">
        ///     Is there a good way to convert between BitmapSource and Bitmap?
        /// </seealso>
        /// </remarks>
        internal static GdiPlus.Bitmap ConvertToGdiPlusBitmap(this Wpf.Media.Imaging.BitmapSource bitmapSource)
        {
            var bmp = new GdiPlus.Bitmap(
                bitmapSource.PixelWidth,
                bitmapSource.PixelHeight,
                GdiPlus.Imaging.PixelFormat.Format32bppPArgb);

            var rectangle = new GdiPlus.Rectangle(GdiPlus.Point.Empty, bmp.Size);
            var data      = bmp.LockBits(
                rectangle,
                GdiPlus.Imaging.ImageLockMode.WriteOnly,
                GdiPlus.Imaging.PixelFormat.Format32bppPArgb
                );

            bitmapSource.CopyPixels(
                Wpf.Int32Rect.Empty,
                data.Scan0,
                data.Height * data.Stride,
                data.Stride);
            bmp.UnlockBits(data);
            return(bmp);
        }
Example #10
0
        public static System.Drawing.Bitmap BitmapSourceToBitmap(System.Windows.Media.Imaging.BitmapSource srs)
        {
            var width  = srs.PixelWidth;
            var height = srs.PixelHeight;
            var stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
            var ptr    = System.IntPtr.Zero;

            try {
                ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(height * stride);
                srs.CopyPixels(new System.Windows.Int32Rect(0, 0, width, height), ptr, height * stride, stride);
                using (var btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppArgb, ptr)) {
                    // Clone the bitmap so that we can dispose it and
                    // release the unmanaged memory at ptr
                    return(new System.Drawing.Bitmap(btm));
                }
            }
            finally {
                if (ptr != System.IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
                }
            }
        }
Example #11
0
        /// <summary>
        /// Converts from WPF BitmapSource type to Windows forms (GDI+) Bitmap.
        /// </summary>
        public static Bitmap ToBitmap(this System.Windows.Media.Imaging.BitmapSource source)
        {
            var bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

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

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

            bmp.UnlockBits(data);

            return(bmp);

            /* This code might be "better" for different formats but it requires unsafe code.
             * System.Drawing.Bitmap bitmap = null;
             *
             *          int width = source.PixelWidth;
             *          int height = source.PixelHeight;
             *          int stride = width * ((source.Format.BitsPerPixel + 7) / 8);
             *
             *          byte[] bits = new byte[height * stride];
             *
             *          source.CopyPixels(bits, stride, 0);
             *
             *          unsafe
             *          {
             *              fixed (byte* pB = bits)
             *              {
             *                  IntPtr ptr = new IntPtr(pB);
             *
             *                  bitmap = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppPArgb, ptr);
             *              }
             *          }
             *
             *          return bitmap; */
        }
        /// <summary>
        /// Returns the glyph associated with a combo entry.
        /// </summary>
        /// <param name="iCombo">[in] The drop-down bar/Window combo.</param>
        /// <param name="iIndex">[in] Index of item of interest.</param>
        /// <param name="piImageIndex">[out] Index of glyph in the image list.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        /// <remarks>
        /// GetImage will only be called if you specified ENTRY_IMAGE for the entry attributes of the given combo. There are two expected return codes from GetImage:
        ///     S_OK: Draw the glyph indicated in *piImageIndex. Use this for entries that should have a glyph.
        ///     S_FALSE: Set aside space for a glyph, but don't draw anything. Use this for entries that don't have a glyph but might have sibling entries in the same combo with glyphs.
        ///     Other: Some other failure occurred.
        ///
        /// Glyphs in your image lists are assumed to be of the same height.
        /// </remarks>
        public int GetEntryImage(int iCombo, int iIndex, out int piImageIndex)
        {
            piImageIndex = 0;
            if (!ValidateIndex(iCombo, iIndex))
            {
                return(VSConstants.E_INVALIDARG);
            }

            var targetGlyph = _navigationControls[iCombo].Item2[iIndex].Glyph;

            if (targetGlyph == null)
            {
                return(VSConstants.S_FALSE);
            }

            int index;

            if (!_glyphIndexes.TryGetValue(new WeakReference <ImageSource>(targetGlyph), out index))
            {
                index = -1;

                // add the image to the image list
                BitmapSource bitmapSource = targetGlyph as BitmapSource;
                if (bitmapSource != null)
                {
                    if (bitmapSource.Format != PixelFormats.Pbgra32 && bitmapSource.Format != PixelFormats.Bgra32)
                    {
                        var formattedBitmapSource = new FormatConvertedBitmap();
                        formattedBitmapSource.BeginInit();
                        formattedBitmapSource.Source            = bitmapSource;
                        formattedBitmapSource.DestinationFormat = PixelFormats.Pbgra32;
                        formattedBitmapSource.EndInit();

                        bitmapSource = formattedBitmapSource;
                    }

                    int    bytesPerPixel = bitmapSource.Format.BitsPerPixel / 8;
                    byte[] data          = new byte[bitmapSource.PixelWidth * bitmapSource.PixelHeight * bytesPerPixel];
                    int    stride        = bitmapSource.PixelWidth * bytesPerPixel;
                    bitmapSource.CopyPixels(data, stride, 0);
                    IntPtr nativeData = Marshal.AllocHGlobal(data.Length);
                    try
                    {
                        Marshal.Copy(data, 0, nativeData, data.Length);
                        PixelFormat pixelFormat = (bitmapSource.Format == PixelFormats.Bgra32) ? PixelFormat.Format32bppArgb : PixelFormat.Format32bppPArgb;
                        Bitmap      bitmap      = new Bitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, stride, pixelFormat, nativeData);
                        _imageList.Images.Add(bitmap);
                        index = _imageList.Images.Count - 1;
                        _glyphIndexes.Add(new WeakReference <ImageSource>(targetGlyph), index);
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(nativeData);
                    }
                }
            }

            if (index >= 0)
            {
                piImageIndex = index;
            }

            return(index >= 0 ? VSConstants.S_OK : VSConstants.S_FALSE);
        }
Example #13
0
 public static Texture2D CreateTexture2DFromMediaBitamp(Device device,MediaBitmapSource bitmapSource)
 {
     int stride = bitmapSource.PixelWidth * 4;
     using (var buffer = new DataStream(bitmapSource.PixelHeight * stride, true, true))
     {
         // Copy the content of the WIC to the buffer
         byte[] array = new byte[bitmapSource.PixelHeight * stride];
         bitmapSource.CopyPixels(array, stride, 0);
         buffer.Write(array, 0, bitmapSource.PixelHeight * stride);
         return new Texture2D(device, new Texture2DDescription()
         {
             Width = bitmapSource.PixelWidth,
             Height = bitmapSource.PixelHeight,
             ArraySize = 1,
             BindFlags = BindFlags.ShaderResource,
             Usage = ResourceUsage.Immutable,
             CpuAccessFlags = CpuAccessFlags.None,
             Format = Format.R8G8B8A8_UNorm,
             MipLevels = 1,
             OptionFlags = ResourceOptionFlags.None,
             SampleDescription = new SampleDescription(1, 0),
         }, new DataRectangle(buffer.DataPointer, stride));
     }
 }