Bitmap To Byte RgbQ - CSharp System.Drawing

CSharp examples for System.Drawing:Image Convert

Description

Bitmap To Byte RgbQ

Demo Code


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

public class Main{

        public unsafe static byte[, ,] BitmapToByteRgbQ(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
            {
                byte* _curpos;
                fixed (byte* _result = result)
                {
                    byte* _red   = _result, 
                          _green = _result + 1, 
                          _blue  = _result + 2;
                    for (var h = 0; h < height; h++)
                    {
                        _curpos = ((byte*)bd.Scan0) + h * bd.Stride;
                        for (var w = 0; w < width; w++)
                        {
                            *_blue = *(_curpos++); 
                             _blue += 3;

                            *_green = *(_curpos++); 
                             _green += 3;

                            *_red = *(_curpos++); 
                             _red += 3;
                        } 
                    }
                }
            }
            finally
            {
                bmp.UnlockBits(bd);
            }
            return result;
        }
}

Related Tutorials