C# - Converting Raw Image to Bitmap

by Bar Zohan 29. October 2010 02:25

Some pointers and unsafe code should be used (sorry there is no other way for processing pixels). Function takes file path as parameter "path" and returns a Bitmap instance of the raw formatted image. 

As raw image format does not provide height and width info of the image contained, you should provide these to the function as w and h.

 

     private Bitmap CreateBitmap(string path,int w,int h)

        {

            FileStream sp = File.Open(path, FileMode.Open);

 

            Rectangle myrect = new Rectangle(0, 0, w, h);

            Bitmap mapImage = new Bitmap(w, h);

            BitmapData bmpData = mapImage.LockBits(myrect, ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);

            int[] mapBitmap = new int[w* h];

            int ptr = bmpData.Scan0.ToInt32();

            unsafe

            {

                for (int y = 0; y < h; y++)

                {

                    for (int x = 0; x < w; x++)

                    {

                        int val = sp.ReadByte();

                        mapBitmap[y * w+ x] = val;

                        if (val == 0)

                            val = Color.Gray.ToArgb();

                        if (val == 255)

                            val = Color.LightYellow.ToArgb();

                        *(int*)(ptr + y * bmpData.Stride + x * 4 + 0) = val;

                    }

                }

 

                mapImage.UnlockBits(bmpData);

            }

            sp.Close();

 

            return mapImage;

        }

 

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Page List