将位图中的字节复制到字节数组然后再用Marshall复制 [英] Copying bytes from Bitmap to byte array and back with Marshall.Copy doesn't work right

查看:119
本文介绍了将位图中的字节复制到字节数组然后再用Marshall复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Marshall.Copy复制字节.我的代码可以工作,但是字节对我来说很奇怪.我认为,索引不是真正的字节.如果计算并保存回去,我会在图像中得到不同的颜色,并且字节大小要大得多(图像大小是相同的).

I want to copy bytes with Marshall.Copy. My code work, but bytes is strange for me. I think, I got indexes not real bytes. If this compute and save back, I got different colors in image with lot bigger byte size (image size is same).

 Bitmap bmp = new Bitmap(imagepath);
    Width = bmp.Width;
    Height = bmp.Height;
    byte[] data;
    BitmapData bdata;
    switch (bmp.PixelFormat)
    {
      case PixelFormat.Format8bppIndexed:
      {
        data = new byte[Width * Height];
        bdata = bmp.LockBits(new Rectangle(0, 0, Width, Height),ImageLockMode.ReadOnly, bmp.PixelFormat);
        Marshal.Copy(bdata.Scan0, data, 0, data.Length);
        bmp.UnlockBits(bdata);
        break;
      }
    }

从字节保存图像:

BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
IntPtr pNative = bmData.Scan0;
Marshal.Copy(data, 0, pNative, Width * Height);
bmp.UnlockBits(bmData);
bmp.Save("output.gif",ImageFormat.Gif); //without format, have same problem

如果我从第一个像素读取颜色,则会得到:Color [A=0, R=0, G=0, B=2].这是输入图像中真正的颜色吗?

If I read color from first pixel, I got: Color [A=0, R=0, G=0, B=2]. Is this really color in input image?

我不知道,为什么输出与输入有很大不同.问题出在哪里?

I don't know, why output is soo different from input. Where is problem?

输入和输出示例(对小图像表示抱歉):

Example from input and output (sorry for small images):

推荐答案

您没有显示如何创建第二个bmp来重新加载字节.但是PixelFormat8bbpIndexed,这意味着您的data数组将包含调色板索引而不是直接的颜色信息.当您创建第二个具有8位像素格式的bmp时,它将使用默认调色板,该调色板可能与原始调色板不同.

You did not show how you created the second bmp for reloading the bytes. But the PixelFormat is 8bbpIndexed, which means that your data array will contain palette indices instead of direct color information. When you create your second bmp with 8 bit pixel format it will use a default palette, which may be different from the original one.

因此,您必须保存第一张图像的bmp.Palette,然后使用它恢复第二张bmp实例的实际颜色.

So you must save the bmp.Palette of the first image, then use it to restore the actual colors of your second bmp instance.

更新:尽管可以一个一个地设置调色板条目,但是它没有任何作用.您必须设置整个调色板.此外,此处是带有索引位图操作(请参见ConvertPixelFormat)方法的帖子.

Update: Though you can set the palette entries one by one, it has no effect. You must set the whole palette instead. Additionally, here is a post with indexed bitmap manipulation (see the ConvertPixelFormat) method.

这篇关于将位图中的字节复制到字节数组然后再用Marshall复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆