コード例 #1
0
ファイル: BitmapExtensions.cs プロジェクト: arnavdas88/dnn
        /// <summary>
        /// Creates an <see cref="Image"/> from an encapsulated GDI+ bitmap.
        /// </summary>
        /// <param name="bitmap">The GDI+ bitmap from which to create the <see cref="Image"/>.</param>
        /// <returns>
        /// The <see cref="Image"/> this method creates.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="bitmap"/> is <b>null</b>.
        /// </exception>
        public static Image FromBitmap(System.Drawing.Bitmap bitmap)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException(nameof(bitmap));
            }

            Image image = new Image(
                bitmap.Width,
                bitmap.Height,
                BitmapExtensions.PixelFormatToBitsPerPixel(bitmap.PixelFormat),
                (int)(bitmap.HorizontalResolution + 0.5f),
                (int)(bitmap.VerticalResolution + 0.5f));

            BitmapData srcData = bitmap.LockBits(
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly,
                bitmap.PixelFormat);

            unsafe
            {
                fixed(ulong *dst = image.Bits)
                {
                    Arrays.CopyStrides(
                        image.Height,
                        srcData.Scan0,
                        srcData.Stride,
                        new IntPtr(dst),
                        image.Stride8);
                }
            }

            if (image.BitsPerPixel < 8)
            {
                Vectors.SwapBits(image.Bits.Length, image.BitsPerPixel, image.Bits, 0);
            }

            bitmap.UnlockBits(srcData);

            return(Image.OnLoaded(
                       image,
                       null,
                       bitmap.Palette?.Entries?.Select(x => Color.FromArgb(x.A, x.R, x.G, x.B)).ToArray()));
        }