1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
//Returns a Texture2D containing the same image as the bitmap parameter, resized if necessary. Returns null if an error occurs.
public Texture2D CreateTextureFromBitmap( GraphicsDevice graphics_device, System.Drawing.Bitmap bitmap )
{
Texture2D texture = null;
bool dispose_bitmap = false;
try
{
if (bitmap != null)
{
//Resize the bitmap if necessary, then capture its final size
if (graphics_device.GraphicsDeviceCapabilities.TextureCapabilities.RequiresPower2)
{
System.Drawing.Size new_size; //New size will be next largest power of two, so bitmap will always be scaled up, never down
new_size = new Size( (int)Math.Pow( 2.0, Math.Ceiling( Math.Log( (double)bitmap.Width ) / Math.Log( 2.0 ) ) ), (int)Math.Pow( 2.0, Math.Ceiling( Math.Log( (double)bitmap.Height ) / Math.Log( 2.0 ) ) ) );
bitmap = new Bitmap( bitmap, new_size );
dispose_bitmap = true;
}
System.Drawing.Size bitmap_size = bitmap.Size;
//Create a texture with an appropriate format
texture = new Texture2D( graphics_device, bitmap_size.Width, bitmap_size.Height, 1, TextureUsage.None, SurfaceFormat.Color );
//Lock the bitmap data and copy it out to a byte array
System.Drawing.Imaging.BitmapData bmpdata = bitmap.LockBits( new System.Drawing.Rectangle( 0, 0, bitmap_size.Width, bitmap_size.Height ), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb );
byte [ ] pixel_bytes = null;
try
{
pixel_bytes = new byte[bmpdata.Stride * bmpdata.Height];
Marshal.Copy( bmpdata.Scan0, pixel_bytes, 0, temp_bytes.Length );
}catch{} //If error occurs allocating memory, bitmap will still be unlocked properly
bitmap.UnlockBits( bmpdata );
//Set the texture's data to the byte array containing the bitmap data that was just copied
if (pixel_bytes != null) texture.SetData<byte>( pixel_bytes );
}
}
catch
{
//Error occured; existing texture must be considered invalid
if (texture != null)
{
texture.Dispose();
texture = null;
}
}
finally
{
if (dispose_bitmap)
bitmap.Dispose();
}
return texture;
} |
Partager