将2bpp灰度图像转换为压缩字节数组

时间:2018-12-12 19:32:09

标签: c# image encoding binary byte

有人可以告诉我将2bpp灰度图像转换为压缩字节数组时出了什么问题吗? 压缩格式为W * H *颜色。

目前,我正在拍摄这张照片。 enter image description here

通过它运行它。.

  public byte[] ToBytes(ImageData imageData)
  {
      byte imageDepth  = 4;
      int  imageWMin   = imageData.GetWidth();
      int  imageHMin   = imageData.GetHeight();
      int  imageWMax   = (int)Math.Ceiling((double)imageData.GetWidth()  / 16) * 16;
      int  imageHMax   = (int)Math.Ceiling((double)imageData.GetHeight() / 16) * 16;
      int  byteCount   = ((imageWMax + imageHMax * imageWMax) * imageDepth) / 256;
      byte[] data = new byte[byteCount];

      //Loop though tiles
      for (int ty = 0; ty < imageHMax/8; ty++)
      for (int tx = 0; tx < imageWMax/8; tx++)
      {
          //Loop through pixels
          for (int py = 0; py < 8; py++)
          for (int px = 0; px < 8; px++)
          {      
              int pixelX     = tx + px;
              int pixelY     = ty + py;
              int pixelColor = 0;
              int pixelByte  = ((pixelX + pixelY * imageWMax) * imageDepth) / 256;

              if (pixelX < imageWMin && pixelY < imageHMin)
                  pixelColor = Math.Min((imageData.GetPixel(pixelX, pixelY).intValue0 / 64), 3);

              Console.WriteLine("{ " + pixelX.ToString() + ", " + pixelY.ToString() + " } = " + pixelColor.ToString() + " at byte: " + pixelByte.ToString());
              data[pixelByte] = (byte)((data[pixelByte] & ~(byte)0x4) | ((byte)pixelColor & (byte)0x4));
          }
      }
      return data;
  }

    public override void Load() //runs on boot
    {
        imageData = Image.NewImageData("test.png");
        image     = Graphics.NewImage(imageData);
        image.SetFilter(FilterMode.Nearest, FilterMode.Nearest, 1);
        bytes     = ToBytes(imageData);

        Console.WriteLine("saving to " + AppDomain.CurrentDomain.BaseDirectory + "test.txt");
        if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "test.txt")) Console.WriteLine("file: " + AppDomain.CurrentDomain.BaseDirectory + "test.txt does not exist!");
        System.IO.File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory+"test.txt", bytes);
    }

    static void Main(string[] arg)
    {
        Boot.Run(new Test2BPP());
    }

并以此获取解码的二进制输出。

04 04 00 00

我猜应该是2个字节而不是4个字节,因为16 * 8 * 4 = 512或2个字节的整数值

因此,为了清楚起见,我想将图像的每个8x8部分从左上到右下保存为一个字节或每个像素2位(TILEWIDTH * TILEHEIGHT * COLORSPERPIXEL)。

如果图像小于x或y轴上的8的幂,则默认将剩余值设置为0。

0 个答案:

没有答案