/// <summary> /// Converts this instance to a <see cref="Bitmap"/> using <see cref="ImageFormat.Bmp"/>. /// </summary> /// <returns>A <see cref="Bitmap"/> that has the format <see cref="ImageFormat.Bmp"/>.</returns> 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); } }
/// <summary> /// Converts this instance to a <see cref="BitmapSource"/>. /// </summary> /// <returns>A <see cref="BitmapSource"/>.</returns> public BitmapSource ToBitmapSource() { string mapping = "RGB"; MediaPixelFormat format = MediaPixelFormats.Rgb24; if (HasAlpha) { mapping = "BGRA"; format = MediaPixelFormats.Bgra32; } if (ColorSpace == ColorSpace.CMYK) { mapping = "CMYK"; format = MediaPixelFormats.Cmyk32; } int step = format.BitsPerPixel / 8; int stride = Width * step; using (PixelCollection pixels = GetPixels()) { byte[] bytes = pixels.ToByteArray(mapping); return(BitmapSource.Create(Width, Height, 96, 96, format, null, bytes, stride)); } }