I'd like to access color info of my 64bpp image with BitmapData. I've succesfully done this for 32bpp images, but it doesn't seem to be as easy for 64bpp images...
static void Main(string[] args)
{
Bitmap bmp;
using (Stream imageStreamSource = new FileStream(bitmapPath, FileMode.Open, FileAccess.Read, FileShare.Read)) //Should I use "using" here? or do I need to keep the stream open for as long as I use the Bitmap?
{
PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
bmp = _bitmapFromSource(bitmapSource);
}
unsafe
{
int xIncr = Image.GetPixelFormatSize(bmp.PixelFormat) / 8; //8
xIncr /= 2;
BitmapData bData1 = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
ushort* bData1Scan0Ptr = (ushort*)bData1.Scan0.ToPointer();
ushort* nextBase = bData1Scan0Ptr + bData1.Stride;
for (int y = 0; y < bData1.Height; ++y)
{
for (int x = 0; x < bData1.Width; ++x)
{
var red = bData1Scan0Ptr[2];
var green = bData1Scan0Ptr[1];
var blue = bData1Scan0Ptr[0];
bData1Scan0Ptr += xIncr; //xIncr = 4
}
bData1Scan0Ptr = nextBase;
nextBase += bData1.Stride;
}
}
}
//http://stackoverflow.com/questions/7276212/reading-preserving-a-pixelformat-format48bpprgb-png-bitmap-in-net
private static Bitmap _bitmapFromSource(BitmapSource bitmapsource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream()) //Should I use "using" here?
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new System.Drawing.Bitmap(outStream);
}
return bitmap;
}
For a white image (255, 255, 255) I get 0 and 32 back as the 2 values...? I don't know if this is correct and I'm just interpreting them wrong or if they're just completely wrong. (not true anymore with updated code)
EDIT: With the updated code I'm getting 8192 for a 255 value and 1768 for a 128 value. This still doesn't make much sense to me...
I was also wondering if I should be using the "using" statement when loading the image, because http://msdn.microsoft.com/en-us/library/z7ha67kw says I need to keep the stream open for the lifetime of the bitmap. It seems to work fine the way it is now, or is that because I copy the bitmap to another bitmap declared outside the "using" statement?