0

I need to extract RGB byte values of each pixel of a small GIF stored on a PC (16x16 pixels) as I need to send them to a LED display that accepts RGB 6 byte color code.

After opening the test file and converting it to a 1D byte array I get some byte values, but I am not sure if that decodes the GIF frame and as a result will return my desired pure 192 byte RGB array?

 'img = Image.FromFile("mygif.gif");               
  FrameDimension dimension = new FrameDimension(img.FrameDimensionsList[0]);
  int frameCount = img.GetFrameCount(dimension);
  img.SelectActiveFrame(dimension, 0);
  gifarray = imageToByteArray(img);`

   //image to array conversion func.
   public byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        return ms.ToArray();

    }

Or maybe there is another method for doing that?

4

2 回答 2

2

使用此方法获取包含像素的二维数组:

//using System.Drawing;
Color[,] getPixels(Image image)
{
    Bitmap bmp = (Bitmap)image;
    Color[,] pixels = new Color[bmp.Width, bmp.Height];

    for (int x = 0; x < bmp.Width; x++)
        for (int y = 0; y < bmp.Height; y++)
            pixels[x, y] = bmp.GetPixel(x, y);

    return pixels;
}

使用此方法返回的数据,您可以获取每个像素的RGBA(每个都是一个字节),并对它们做任何你想做的事情。

如果您希望最终结果是byte[]包含这样的值:{ R0, G0, B0, R1, G1, B1, ... },并且像素需要按byte[]行主要顺序写入,那么您可以这样做:

byte[] getImageBytes(Image image)
{
    Bitmap bmp = (Bitmap)image;
    byte[] bytes = new byte[(bmp.Width * bmp.Height) * 3]; // 3 for R+G+B

    for (int x = 0; x < bmp.Width; x++)
    {
        for (int y = 0; y < bmp.Height; y++)
        {
            Color pixel = bmp.GetPixel(x, y);
            bytes[x + y * bmp.Width + 0] = pixel.R;
            bytes[x + y * bmp.Width + 1] = pixel.G;
            bytes[x + y * bmp.Width + 2] = pixel.B;
        }
    }

    return bytes;
}

然后,您可以将结果发送getImageBytes到您的 LED(假设这就是您应该向其发送图像的方式)。

于 2013-07-02T21:03:13.350 回答
1

您的方式不会将其解码为原始 RGB 字节数据。它很可能会输出您在开始时加载的相同数据(GIF 编码)。

您将需要逐像素提取数据:

public byte[] imageToByteArray(Image imageIn)
{
    Bitmap lbBMP = new Bitmap(imageIn);
    List<byte> lbBytes = new List<byte>();

    for(int liY = 0; liY < lbBMP.Height; liY++)
        for(int liX = 0; liX < lbBMP.Width; liX++)
        {
            Color lcCol = lbBMP.GetPixel(liX, liY);
            lbBytes.AddRange(new[] { lcCol.R, lcCol.G, lcCol.B });
        }

    return lbBytes.ToArray();
}
于 2013-07-02T19:42:00.893 回答