I need to copy part of the image from bitmap to Texture2D. I know how to copy part of an image from Bitmap, but how to convert it to Texture2D?

  • Do you know how to copy the whole image? - VladD
  • Unfortunately not. I know that I need to use the Bitmap.Clone method, but I don’t know how to turn it into a Digestable for Texture2D view. Actually, this is the question. Apparently, he incorrectly formulated, now I will correct it. - kapucin2

1 answer 1

Apparently, an adaptation of this answer should come up:

using System.Drawing; using System.Drawing.Imaging; GraphicsDevice device = ...; Bitmap bitmap = ...; Texture2D tex = new Texture2D(device, w, h, 1, TextureUsage.None, SurfaceFormat.Color); BitmapData data = bitmap.LockBits( new Rectangle(startx, starty, w, h), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { int bpp = Image.GetPixelFormatSize(bitmap.PixelFormat); if (bpp != 32) thrpw new ArgumentException("ARGB image expected"); int bufferSize = w * h * (bpp / 8); //create data buffer byte[] bytes = new byte[bufferSize]; // copy bitmap data into buffer for (int y = 0; y < h; y++) Marshal.Copy( data.Scan0 + y * data.Stride, bytes, y * w, w); // copy our buffer to the texture tex.SetData(bytes); } finally { // unlock the bitmap data bitmap.UnlockBits(data); } 

Here w , h - the size of your piece, startx , starty - the initial x - and y position of your piece.

Note that the following answer states that you still need to deploy BGRA to RGBA.


Update: this answer suggests that SurfaceFormat.Color ARGB format. This means that a picture with 24 bpp will not work.

  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin