Reputation: 2503
using (MemoryStream ms = new MemoryStream(byteSource))
{
var img = (Bitmap)Image.FromStream(ms);
}
I get a Parameter Not Valid error. My question is: Does it matter what the byteSource is? I mean, can it be an arbitrary array of bytes? Or must it already be in an image format? If I were to pass the function an array of, say 0xff, or 0x00 or whatever, within length limitations, does it matter? I'm trying to diagnose the cause of the parameter not valid error.
Upvotes: 2
Views: 6367
Reputation: 164291
Yes, the byte stream needs to be in a valid image format, ie. a .png, jpg or similar file. Where do you have the byteSource
from ? If it is an array of pixel values, you need to create a new bitmap, then use LockBits
to get an array you can copy bytes to in the correct format.
If that is what you are looking for, here is an example that fills a 100x100 image with noise:
Bitmap b = new Bitmap(100,100);
var bits = b.LockBits(new Rectangle(0,0,100,100), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Random rand = new Random();
var pixels = Enumerable.Range(1, 100*100).Select(n => rand.Next()).ToArray();
Marshal.Copy(pixels, 0, bits.Scan0, 100*100);
b.UnlockBits(bits);
// use the image ...
b.Save("D:\\test.png", ImageFormat.Png);
This assumes that your source of pixels are 32bppArgb, but there are other format options you can pass to LockBits.
Upvotes: 2