C# LockBits perfomance (int[,] to byte[])

后端 未结 5 1276
滥情空心
滥情空心 2020-12-21 06:26
Graphics g;
using (var bmp = new Bitmap(_frame, _height, PixelFormat.Format24bppRgb))
{
    var data = bmp.LockBits(new Rectangle(0, 0, _frame, _height), ImageLockMo         


        
5条回答
  •  执念已碎
    2020-12-21 06:29

    I totally agree with Guffa's answer. Using an unsafe code block will speed up things. To further improve performance, you could execute your for loop in parallel by using the Parallel class in the .Net framework. For large bitmaps this improves performance. Here is a small code sample:

    using (Bitmap bmp = (Bitmap)Image.FromFile(@"mybitmap.bmp"))
    {
      int width = bmp.Width;
      int height = bmp.Height;
    
      BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height),
        System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
    
      byte* s0 = (byte*)bd.Scan0.ToPointer();
      int stride = bd.Stride;
    
      Parallel.For(0, height, (y1) =>
      {
        int posY = y1*stride;
        byte* cpp = s0 + posY;
    
        for (int x = 0; x < width; x++)
        {              
          // Set your pixel values here.
          cpp[0] = 255;
          cpp[1] = 255;
          cpp[2] = 255;
          cpp += 3;
        }
      });
    
      bmp.UnlockBits(bd);
    }
    

    To keep the example simple I've set the pixel values to a constant value. Note, to compile the example above you have to allow unsafe code.

    Hope, this helps.

提交回复
热议问题