Search code examples
c#imagexnaloadingtexture2d

XNA and loading images from files


I found way to load images directly from files, but image that i load is blue (original is green). I tought that it's saved in bad way, so i saved it with photoshop, but nothing changed. I guess that my program works bad. How can i change it and is it good way to load images from files? Bitmap to texture2d method:

    public static Texture2D GetTexture2DFromBitmap(GraphicsDevice device, Bitmap bitmap)
    {
        Texture2D tex = new Texture2D(device, bitmap.Width, bitmap.Height);
        System.Drawing.Imaging.BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
        int bufferSize = data.Height * data.Stride;
        byte[] bytes = new byte[bufferSize];
        System.Runtime.InteropServices.Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
        tex.SetData(bytes);
        bitmap.UnlockBits(data);
        return tex;
    }

Loading image line:

        backgroundTexture = Tools.GetTexture2DFromBitmap(device, (System.Drawing.Bitmap)System.Drawing.Image.FromFile(@"1.bmp", false));

Drawning texture method:

        spriteBatch.Begin();
        Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);
        spriteBatch.Draw(backgroundTexture, screenRectangle, Color.White);
        spriteBatch.End();

Solution

  • Ummm.... I think is easier to load image files through the Texture2D.FromStream method...

    texture = Texture2D.FromStream(Device, File.OpenRead(path));

    Yes, it only loads jpg, png and gif images, but whats the matter with that? ... converting a bmp is easy..