使用MemoryStream时参数无效

时间:2015-03-09 17:06:39

标签: c# bitmap bit-manipulation memorystream

我在c#中制作了一些Bitmap图像处理应用程序,所以我需要隐式地将图像转换为bmp,这样我就可以像byte [](字节数组)一样操作它。当这个图像不是bmp格式时会出现问题 - 在这种情况下,我将它转换为Bitmap后,我将这个Bitmap转换为byte []并应用了一些函数(顺便说一下我和#34;避免"前53个字节 - 标题字节)应用程序中断,我得到"参数无效"尝试在此byte []上使用MemoryStream实例化新Bitmap时发出错误信息。

这是代码:

public void load(PictureBox pom)
{
    OpenFileDialog o = new OpenFileDialog();

    //o.Filter = "bin files (*.bin)|*.bin";

    if (o.ShowDialog() == DialogResult.OK)
    {
        Bitmap b = (Bitmap)Image.FromFile(o.FileName);

        pom.Image = b;

        //pom.Image = new Bitmap(o.FileName);
        this.p = pom;
        this.input_bin_fajl = File.ReadAllBytes(o.FileName);
        this.output_bin_fajl = new byte[this.input_bin_fajl.Length];
    }
}

public static Bitmap ByteToImage(byte[] blob)
{
    using (MemoryStream mStream = new MemoryStream())
    {
        mStream.Write(blob, 0, blob.Length);
        mStream.Seek(0, SeekOrigin.Begin);

        // this is the breaking point
        Bitmap bm = new Bitmap(mStream);
        //

        return bm;
    }
}

1 个答案:

答案 0 :(得分:0)

以下是它不安全的代码再次感谢:)

    void preview(Bitmap bm, int i)
    {
        BitmapData bmData = bm.LockBits(new Rectangle(0,0,bm.Width,bm.Height), ImageLockMode.ReadWrite, bm.PixelFormat);
        int stride = bmData.Stride;
        System.IntPtr Scan0 = bmData.Scan0;

        unsafe
        {
            byte* p = (byte*)(void*)Scan0;
            int nOffset = stride - bm.Width * 3;
            int nWidth = bm.Width * 3;

            for (int y = 0; y < bm.Height; ++y)
            {
                for (int x = 0; x < bm.Width; ++x)
                {
                    switch (i)
                    {
                        case 0:
                            {
                                p[0] = (byte)0;
                                p[1] = (byte)0;
                                break;
                            }
                        case 1:
                            {
                                p[0] = (byte)0;
                                p[2] = (byte)0;
                                break;
                            }
                        default:
                            {
                                p[1] = (byte)0;
                                p[2] = (byte)0;
                                break;
                            }                               
                    }
                    p+=3;
                }
                p += nOffset;
            }
        }

        bm.UnlockBits(bmData);
    }