private static void SetBitmapDensity <TQuantumType>(IMagickImage <TQuantumType> image, Bitmap bitmap, bool useDpi)
     where TQuantumType : struct
 {
     if (useDpi)
     {
         var dpi = image.GetDefaultDensity(useDpi ? DensityUnit.PixelsPerInch : DensityUnit.Undefined);
         bitmap.SetResolution((float)dpi.X, (float)dpi.Y);
     }
 }
Exemplo n.º 2
0
        private static BitmapSource ToBitmapSource <TQuantumType>(this IMagickImage <TQuantumType> self, bool useDensity)
            where TQuantumType : struct
        {
            Throw.IfNull(nameof(self), self);

            IMagickImage <TQuantumType> image = self;

            var mapping = "RGB";
            var format  = MediaPixelFormats.Rgb24;

            try
            {
                if (self.ColorSpace == ColorSpace.CMYK && !image.HasAlpha)
                {
                    mapping = "CMYK";
                    format  = MediaPixelFormats.Cmyk32;
                }
                else
                {
                    if (image.ColorSpace != ColorSpace.sRGB)
                    {
                        image            = self.Clone();
                        image.ColorSpace = ColorSpace.sRGB;
                    }

                    if (image.HasAlpha)
                    {
                        mapping = "BGRA";
                        format  = MediaPixelFormats.Bgra32;
                    }
                }

                var step   = format.BitsPerPixel / 8;
                var stride = image.Width * step;

                using (var pixels = image.GetPixelsUnsafe())
                {
                    var bytes = pixels.ToByteArray(mapping);
                    var dpi   = image.GetDefaultDensity(useDensity ? DensityUnit.PixelsPerInch : DensityUnit.Undefined);
                    return(BitmapSource.Create(image.Width, image.Height, dpi.X, dpi.Y, format, null, bytes, stride));
                }
            }
            finally
            {
                if (!ReferenceEquals(self, image))
                {
                    image.Dispose();
                }
            }
        }