I am creating images with a byte[]
array in C#, and then converting them to a Bitmap
in order to save them to disk.
Here's a few extracts from my code:
// Create an array of RGB pixels
byte[] pixels = new byte[width * height * 3];
// Do some processing here....
// Import the pixel data into a new bitma
Bitmap image = new Bitmap(width, height, width * 3, PixelFormat.Format24bppRgb, GCHandle.Alloc(pixels, GCHandleType.Pinned).AddrOfPinnedObject());
// Save the image
image.Save("testimage.png", ImageFormat.Png);
This works well, until the width / height aren't a power of 2 (i.e. 512x512 works, but 511x511 doesn't), and then I get the following error:
Unhandled Exception: System.ArgumentException: Parameter is not valid.
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, Int32 stride, PixelFormat format, IntPtr scan0)
(.......)
For reference, here are my using
statements:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Diagnostics;
Why doesn't it work with pixel data sets that don't have size that's power of 2? How can I make it work with such sizes?
Micke is right, the main reason is that in 32 bit size of register is 4 byte so to optimize speed and efficiency it should be multiple of 4, Source