【问题标题】:How to convert a Bitmap Image to IntPtr in C#?如何在 C# 中将位图图像转换为 IntPtr?
【发布时间】:2009-08-20 01:26:04
【问题描述】:

我是根据我看到的一个示例制作的,它从未抛出任何错误,但图像显示为灰色。

有没有更好的方法来做到这一点?

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参数的构造函数?

标签: c# bitmap intptr


【解决方案1】:

试试这个,

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);
}

【讨论】:

  • 之后别忘了解锁这些位! bmp.UnlockBits(bd);
  • 同意!感谢您的评论。供进一步参考 - stackoverflow.com/questions/133958/…
  • 我的崩溃了,直到我改变了像素格式:BitmapData bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
【解决方案2】:

如果我理解正确,您正在尝试加载 .bmp 文件。为此,只需使用Image.FromFile()。然后,你可以用它做任何你想做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2011-04-24
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    相关资源
    最近更新 更多