简体   繁体   中英

How to convert a Bitmap Image to IntPtr in C#?

I made this from an example i saw, it never threw any error, but the image is displayed as grey.

Is there a better way to do this?

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: I checked the csproj to allow unsafe code in the build.

Try this,

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

If I understand correctly, you're trying to load a .bmp file. To do that, just use Image.FromFile() . Then, you can do whatever you want with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM