Bitmap To Byte Rgb Marshal - CSharp System.Drawing

CSharp examples for System.Drawing:Image Convert

Description

Bitmap To Byte Rgb Marshal

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.InteropServices;
using System.Linq;
using System.IO;//from   w w  w .jav a  2s. co  m
using System.Drawing.Imaging;
using System.Drawing;
using System.Collections.Generic;
using System;

public class Main{
        public unsafe static byte[] BitmapToByteRgbMarshal(Bitmap bmp)
        {
            int width = bmp.Width,
                height = bmp.Height;
            var result = new byte[3 * height * width];
            var bd = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly,
                PixelFormat.Format24bppRgb);
            try
            {
                var lineSize = width * 3;
                for (var h = 0; h < height; h++)
                {
                    var pos = h * lineSize;
                    var curpos = (IntPtr)((byte*)bd.Scan0) + h * bd.Stride;
                    Marshal.Copy(curpos, result, pos, lineSize);
                }
            }
            finally
            {
                bmp.UnlockBits(bd);
            }
            return result;
        }
}

Related Tutorials