Advertisement
Guest User

very fast 1bpp convert

a guest
Mar 24th, 2010
3,118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | None | 0 0
  1.         private static unsafe void Convert(Bitmap src, Bitmap conv)
  2.         {
  3.             // Lock source and destination in memory for unsafe access
  4.             var bmbo = src.LockBits(new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadOnly,
  5.                                      src.PixelFormat);
  6.             var bmdn = conv.LockBits(new Rectangle(0, 0, conv.Width, conv.Height), ImageLockMode.ReadWrite,
  7.                                      conv.PixelFormat);
  8.  
  9.             var srcScan0 = bmbo.Scan0;
  10.             var convScan0 = bmdn.Scan0;
  11.  
  12.             var srcStride = bmbo.Stride;
  13.             var convStride = bmdn.Stride;
  14.  
  15.             byte* sourcePixels = (byte*)(void*)srcScan0;
  16.             byte* destPixels = (byte*)(void*)convScan0;
  17.  
  18.             var srcLineIdx = 0;
  19.             var convLineIdx = 0;
  20.             var hmax = src.Height-1;
  21.             var wmax = src.Width-1;
  22.             for (int y = 0; y < hmax; y++)
  23.             {
  24.                 // find indexes for source/destination lines
  25.  
  26.                 // use addition, not multiplication?
  27.                 srcLineIdx += srcStride;
  28.                 convLineIdx += convStride;
  29.  
  30.                 var srcIdx = srcLineIdx;
  31.                 for (int x = 0; x < wmax; x++)
  32.                 {
  33.                     // index for source pixel (32bbp, rgba format)
  34.                     srcIdx += 4;
  35.                     //var r = pixel[2];
  36.                     //var g = pixel[1];
  37.                     //var b = pixel[0];
  38.  
  39.                     // could just check directly?
  40.                     //if (Color.FromArgb(r,g,b).GetBrightness() > 0.01f)
  41.                     if (!(sourcePixels[srcIdx] == 0 && sourcePixels[srcIdx + 1] == 0 && sourcePixels[srcIdx + 2] == 0))
  42.                     {
  43.                         // destination byte for pixel (1bpp, ie 8pixels per byte)
  44.                         var idx = convLineIdx + (x >> 3);
  45.                         // mask out pixel bit in destination byte
  46.                         destPixels[idx] |= (byte)(0x80 >> (x & 0x7));
  47.                     }
  48.                 }
  49.             }
  50.             src.UnlockBits(bmbo);
  51.             conv.UnlockBits(bmdn);
  52.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement