1
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace MrXNAHelper { public class ImageToTexture { byte[] bmpBytes; Texture2D background; int width, height; Game game; public ImageToTexture(Game game, int width, int height) { this.width = width; this.height = height; this.game = game; GenerateBitmap(game, width, height); } public ImageToTexture(Game game) { this.game = game; } private void GenerateBitmap(Game game, int width, int height) { background = new Texture2D(game.GraphicsDevice, width, height); } public Texture2D ConvertBitmapToTexture(Bitmap b) { game.GraphicsDevice.Textures[0] = null; if (background == null || b.Width != background.Width || b.Height != background.Height) { width = b.Width; height = b.Height; GenerateBitmap(game, width, height); } BitmapData bData = b.LockBits(new System.Drawing.Rectangle(new System.Drawing.Point(), b.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb); // number of bytes in the bitmap int byteCount = bData.Stride * b.Height; if (bmpBytes == null || bmpBytes.Length != byteCount) bmpBytes = new byte[byteCount]; // Copy the locked bytes from memory Marshal.Copy(bData.Scan0, bmpBytes, 0, byteCount); // don't forget to unlock the bitmap!! b.UnlockBits(bData); background.SetData(bmpBytes); return background; } } }2
public static Bitmap FastTextureToBitmap(Texture2D texture) { // Setup pointer back to bitmap Bitmap newBitmap = new Bitmap(texture.Width, texture.Height); // Get color data from the texture Microsoft.Xna.Framework.Graphics.Color[ textureColors = GetColorDataFromTexture(texture); System.Drawing.Imaging.BitmapData bmpData = newBitmap.LockBits(new System.Drawing.Rectangle(0, 0, newBitmap.Width, newBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // Loop through pixels and set values unsafe { byte* bmpPointer = (byte*)bmpData.Scan0; for (int y = 0; y < texture.Height; y++) { for (int x = 0; x < texture.Width; x++) { bmpPointer[0] = textureColors[x + y * texture.Width].B; bmpPointer[1] = textureColors[x + y * texture.Width].G; bmpPointer[2] = textureColors[x + y * texture.Width].R; bmpPointer[3] = textureColors[x + y * texture.Width].A; bmpPointer += 4; } bmpPointer += bmpData.Stride - (bmpData.Width * 4); } } textureColors = null; newBitmap.UnlockBits(bmpData); return newBitmap; }