如何在C#中将位图图像转换为IntPtr?

4

我是从一个例子中制作的,没有抛出任何错误,但图像显示为灰色。

有更好的方法吗?

private unsafe void menuItem7_Click(object sender, EventArgs e)
    {
        var settings = Utility.GatherLocalSettings();

        openFileDialog1.InitialDirectory = settings.SavePath;
        openFileDialog1.Filter = "Scan Files (*.jpg)|*.jpg";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            byte[] openFile = File.ReadAllBytes(openFileDialog1.FileName);
            fixed (byte* p = openFile)
            {
                IntPtr img = (IntPtr)p;

                frmContainer newScan = new frmContainer(img);
                newScan.MdiParent = this;
                newScan.Text = Path.GetFileName(openFileDialog1.FileName) + " [Saved]";
                newScan.Show();
            }
        }

    }

PS:我检查了csproj,允许在构建过程中使用不安全的代码。


你能发布frmContainer的代码吗?或者只是它接受IntPtr参数的构造函数? - MusiGenesis
2个回答

6

尝试一下这个:

IntPtr pval = IntPtr.Zero;
System.Drawing.Imaging.BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
try
{
    pval=bd.Scan0;

    ...
}
finally
{
    bmp.UnlockBits(bd);
}

3
别忘了在操作完成后解锁这些位!bmp.UnlockBits(bd)。 - glenneroo
同意!感谢您的评论。更多参考信息请查看 - https://dev59.com/RkXRa4cB1Zd3GeqPqk4t - KV Prajapati
我的程序一直崩溃,直到我改变了像素格式:BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat); - Luke Dupin

1

如果我理解正确,您正在尝试加载一个 .bmp 文件。要做到这一点,只需使用 Image.FromFile()。然后,您可以随心所欲地处理它。


这个问题是关于如何将BMP转换为IntPtr的,也许他必须在之后详细说明文件,并且一些图像处理需要使用不安全代码完成。 - Payedimaunt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接