如何在C#XNA中访问位图的宽度和高度?

时间:2012-04-22 22:47:56

标签: c# bitmap xna argumentexception

我正在尝试创建一个应用程序,我在其中创建一个Bitmap,然后从中取出一些变量并从中创建一个Texture2D。这就是我所拥有的:

public Bitmap getBitmap()
        {
            if (!panelVideoPreview.IsDisposed)
            {
                Bitmap b = new Bitmap(panelVideoPreview.Width, panelVideoPreview.Height, PixelFormat.Format32bppRgb);
                Graphics g = Graphics.FromImage(b);
                Rectangle videoRect = panelVideoPreview.Bounds;
                panelVideoPreview.DrawToBitmap(b, videoRect);
                b.Dispose();
                return b;
            }
            else
            {
                Bitmap b = new Bitmap(panelVideoPreview.Width, panelVideoPreview.Height);
                return b;
            }
        }

然后我尝试从中创建一个纹理:

        Texture2D tex = new Texture2D(gDevice, (int)bit.Width, (int)bit.Height);

这是我收到错误的地方,我明白了:

  

System.ArgumentException未处理     消息=参数无效。     来源= System.Drawing中     堆栈跟踪:          在System.Drawing.Image.get_Width()          at GPUParticles.VelocityTexture.createVelocityMapBitmap(GraphicsDevice gDevice,Bitmap bit,Single Accuracy)在D:\ Dropbox \ School \ Project FUN \ Code \ XNA \ GPUParticles \ GPUParticles \ GPUParticles \ VelocityTexture.cs:第16行          在D:\ Dropbox \ School \ Project FUN \ Code \ XNA \ GPUParticles \ GPUParticles \ GPUParticles \ Game1.cs中的GPUParticles.Game1.camInterval_Tick(Object myObject,EventArgs myEventArgs):第302行          在System.Windows.Forms.Timer.OnTick(EventArgs e)          在System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)          在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)          在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)          在System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 reason,Int32 pvLoopData)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,ApplicationContext context)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason,ApplicationContext context)          在System.Windows.Forms.Application.Run(Form mainForm)          在Microsoft.Xna.Framework.WindowsGameHost.Run()          在Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)          在Microsoft.Xna.Framework.Game.Run()          在D:\ Dropbox \ School \ Project FUN \ Code \ XNA \ GPUParticles \ GPUParticles \ GPUParticles \ Program.cs中的GPUParticles.Program.Main(String [] args):第15行     InnerException:

1 个答案:

答案 0 :(得分:1)

您可以使用MemoryStream。示例(未经测试):

Texture2D MakeTextureFromBitmap(Bitmap bmp) {
    using (var ms = new MemoryStream()) {
        bmp.Save(ms, ImageFormat.Png);
        return Texture2D.FromStream(GraphicsDevice, ms);
    }
}