Re: key to speed - use byte array instead of writing to locked image bytes
- From: "Frank Hileman" <frankhil@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 1 Feb 2007 15:30:22 -0800
Hi James,
Here is the C# code, it works fine in VB since you don't need any pointers,
you just modify integers in the pixels array. Don't forget to Free the
handle when you are completely finished with the bitmap. The "pixels" array
is an array of uint (unsigned integer). You can use signed integer but it is
more tricky to deal with the top bit. You can access the blue channel with a
0xFF mask, green with 0xFF00, etc. Or you can use an array of bytes, but
that isn't as fast.
// 4 bytes per pixel, format: ARGB
pixels = new uint[width * height];
// if not pinned the GC can move around the array
handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
IntPtr pointer = Marshal.UnsafeAddrOfPinnedArrayElement(pixels, 0);
bitmap = new Bitmap(width , height, width * 4,
PixelFormat.Format32bppPArgb, pointer);
To access a pixel on the bitmap at x and y:
pixel at (x,y) = pixels[width * y + x]
Any modification to that array modifies the bitmap directly. No marshall or
copy needed.
Regards,
Frank Hileman
check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio graphics editor
"James Maeding" <jmaeding@xxxxxxxxxxx> wrote in message
news:i30ir298ipppfgkqfh6mq113o5gd17jefs@xxxxxxxxxx
wow, can you point to any example code, I am intermediate at .net so that
will help me put things together.
I'll check out your site too.
thanks for the tip, this should be fun.
"Frank Hileman" <frankhil@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
|>The fastest method is to avoid any copy of pixels. Since the Bitmap
|>constructor accepts a pointer to a pixel buffer, you only have to
convert a
|>managed array of uint or byte to an IntPtr using GCHandle.Alloc to
obtain a
|>pinned handle and Marshall.UnsafeAddrOfPinnedArrayElement to convert to
an
|>IntPtr. Modifying the array contents will modify the pixels/memory
within
|>the Bitmap directly. LockBits is not needed.
|>
|>You don't need unsafe code or pointer arithmetic (pointers add no
speed),
|>and it is screaming fast, assuming your format is
|>PixelFormat.Format32bppPArgb.
.
- Prev by Date: Re: vb.net Multipage TIFF
- Next by Date: Re: Loading image byte array
- Previous by thread: vb.net Multipage TIFF
- Next by thread: Using TextRenderer MeasureText to find word position - any ideas?
- Index(es):
Relevant Pages
|