public Bitmap ToBitmap()
{
if (ColorSpace == ColorSpace.CMYK)
ColorSpace = ColorSpace.sRGB;
string mapping = "BGR";
PixelFormat format = PixelFormat.Format24bppRgb;
if (HasAlpha)
{
mapping = "BGRA";
format = PixelFormat.Format32bppArgb;
}
using (PixelCollection pixels = GetPixels())
{
Bitmap bitmap = new Bitmap(Width, Height, format);
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, format);
IntPtr destination = data.Scan0;
for (int y = 0; y < Height; y++)
{
byte[] bytes = pixels.ToByteArray(0, y, Width, 1, mapping);
Marshal.Copy(bytes, 0, destination, bytes.Length);
destination = new IntPtr(destination.ToInt64() + data.Stride);
}
bitmap.UnlockBits(data);
return bitmap;
}
}