开发者

How to convert a raw binary image in 2-2-2-2 format into a bitmap in C#?

I am new to C# and I am trying to produce an image from a raw binary stream. The file is a pure binary file with a .bin extension and coded in the 8 bpp 2-2-2-2 format; it contains 2 bits for each RGB color and 2 bits for opacity. I have not tried anything yet because I really do not know where to start; I have searched for previous questions posted but have not find anything useful. My application will be receiving a serial stream and I have to produce an 800 x 600 image from the file using one byte for ev开发者_如何学Goery pixel. Any ideas that will at least get me started?


I would start with something like this.

public void ImageTest()
{
    var bitmap = new Bitmap(800,600);
    var stream = new BinaryReader(new FileStream("pathtofile",FileMode.Open));
    byte currentbyte;
    int x = 0;
    int y = 0;
    while((currentbyte = stream.ReadByte()) != EndOfImageMarker)
    {
        bitmap.SetPixel(x,y,DecodeByteToColor(currentbyte));
        x++;
        y++;
        if (x == 799)//next line
        {
            x = 0;
        }
        if (y == 599)
        {
            break;
        }
    }
    bitmap.Save("Path to new file...");
}

private Color DecodeByteToColor(byte currentbyte)
{
    const int adjustment = 10;
    var red =  (currentbyte & 0x3) * adjustment;
    var green = (currentbyte << 2 & 0x3) * adjustment;
    var blue = (currentbyte << 4 & 0x3) * adjustment;
    var alpha = (currentbyte << 6 & 0x3) * adjustment;
    return Color.FromArgb(red, green, blue, alpha);
}

It has been a while since doing bit shift stuff I may have the operator backwards from what you need. The intent is to grab the first two bits, and shift it for the next two. The adjustment will determine how much color each bit gets once translated to the full range of values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜