示例#1
0
        private static void TestBmpEncoderCore <TPixel>(
            TestImageProvider <TPixel> provider,
            BmpBitsPerPixel bitsPerPixel,
            bool supportTransparency     = true, // if set to true, will write a V4 header, otherwise a V3 header.
            IQuantizer quantizer         = null,
            ImageComparer customComparer = null)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            using (Image <TPixel> image = provider.GetImage())
            {
                // There is no alpha in bmp with less then 32 bits per pixels, so the reference image will be made opaque.
                if (bitsPerPixel != BmpBitsPerPixel.Pixel32)
                {
                    image.Mutate(c => c.MakeOpaque());
                }

                var encoder = new BmpEncoder
                {
                    BitsPerPixel        = bitsPerPixel,
                    SupportTransparency = supportTransparency,
                    Quantizer           = quantizer ?? KnownQuantizers.Octree
                };

                // Does DebugSave & load reference CompareToReferenceInput():
                image.VerifyEncoder(provider, "bmp", bitsPerPixel, encoder, customComparer);
            }
        }
        public static BitmapImage ImageToBitmap(Image image)
        {
            // Possible memory leak?
            // Create memory stream
            MemoryStream ms = new MemoryStream();

            // Create encoder
            var encoder = new BmpEncoder
            {
                BitsPerPixel        = BmpBitsPerPixel.Pixel32,
                SupportTransparency = true
            };

            // Save the image to stream
            image.Save(ms, encoder);

            // Create a bmp image
            var bitmap = new BitmapImage();

            bitmap.BeginInit();
            bitmap.StreamSource = ms;
            bitmap.EndInit();

            return(bitmap);
        }
示例#3
0
        public void Encode_8BitColor_WithOctreeQuantizer <TPixel>(TestImageProvider <TPixel> provider)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            if (!TestEnvironment.Is64BitProcess)
            {
                return;
            }

            using (Image <TPixel> image = provider.GetImage())
            {
                var encoder = new BmpEncoder
                {
                    BitsPerPixel = BmpBitsPerPixel.Pixel8,
                    Quantizer    = new OctreeQuantizer()
                };
                string actualOutputFile = provider.Utility.SaveTestOutputFile(image, "bmp", encoder, appendPixelTypeToFileName: false);

                // Use the default decoder to test our encoded image. This verifies the content.
                // We do not verify the reference image though as some are invalid.
                IImageDecoder referenceDecoder = TestEnvironment.GetReferenceDecoder(actualOutputFile);
                using (var referenceImage = Image.Load <TPixel>(actualOutputFile, referenceDecoder))
                {
                    referenceImage.CompareToReferenceOutput(
                        ImageComparer.TolerantPercentage(0.01f),
                        provider,
                        extension: "bmp",
                        appendPixelTypeToFileName: false,
                        decoder: new MagickReferenceDecoder(false));
                }
            }
        }
            public void SaveAsPdfBitmap(MemoryStream ms)
            {
                BmpEncoder bmp = new BmpEncoder {
                    BitsPerPixel = BmpBitsPerPixel.Pixel32
                };

                Image.Save(ms, bmp);
            }
示例#5
0
 public DibEncoder()
 {
     encoder = new BmpEncoder()
     {
         BitsPerPixel        = BmpBitsPerPixel.Pixel32,
         SupportTransparency = true
     };
 }
示例#6
0
        private static void WriteBmpFrame(CommandLineOptions opts, ParseContext context, IcoFrame frame)
        {
            var encoding = opts.BitmapEncodingOverride ?? BmpUtil.GetIdealBitmapEncoding(frame.CookedData, hasIcoMask: true);

            if (opts.MaskImagePath != null)
            {
                var maskSource = File.ReadAllBytes(opts.MaskImagePath);
                using (var stream = new MemoryStream(maskSource))
                {
                    var decoder = new SixLabors.ImageSharp.Formats.Bmp.BmpDecoder();
                    var mask    = decoder.Decode <Rgba32>(new Configuration(), stream);
                    if (mask.Width != frame.CookedData.Width || mask.Height != frame.CookedData.Height)
                    {
                        Reporter.ErrorLine(
                            IcoErrorCode.BitmapMaskWrongDimensions,
                            $"The mask's dimentions {mask.Height}x{mask.Width} don't match "
                            + $"the frame dimensions {frame.CookedData.Height}x{frame.CookedData.Width}.",
                            opts.MaskImagePath);
                        throw new ArgumentException();
                    }

                    for (var x = 0; x < mask.Width; x++)
                    {
                        for (var y = 0; y < mask.Height; y++)
                        {
                            if (mask[x, y].PackedValue != 0xffffffff && mask[x, y].PackedValue != 0x000000ff)
                            {
                                Reporter.ErrorLine(
                                    IcoErrorCode.BitampMaskWrongColors,
                                    $"The mask must be comprised entirely of black and white pixels (where black means transparent).",
                                    opts.MaskImagePath);
                                throw new ArgumentException();
                            }
                        }
                    }

                    frame.Mask = BmpUtil.CreateMaskFromImage(mask, blackIsTransparent: true);
                }
            }
            else
            {
                frame.Mask = BmpUtil.CreateMaskFromImage(frame.CookedData, blackIsTransparent: false);
            }

            frame.RawData = BmpEncoder.EncodeBitmap(context, encoding, BmpEncoder.Dialect.Ico, frame);
            if (frame.RawData == null)
            {
                Reporter.ErrorLine(context.LastEncodeError, $"Cannot encode the source image as a bitmap of type: {encoding}. Try reducing the number of colors, or changing the bitmap encoding.", opts.SourceImagePath);
                throw new ArgumentException();
            }

            frame.Encoding.ClaimedBitDepth = (uint)BmpUtil.GetBitDepthForPixelFormat(encoding);
            frame.Encoding.ActualBitDepth  = frame.Encoding.ClaimedBitDepth;
        }
示例#7
0
        static void SetupPalette(byte[] palette)
        {
            if (palette.GetHashCode() != _currentPaletteHash)
            {
                _encoder = new BmpEncoder
                {
                    BitsPerPixel = BmpBitsPerPixel.Pixel8,
                    Quantizer    = new PaletteQuantizer(palette.ToImageSharpColors(), new QuantizerOptions {
                        Dither = null
                    })
                };

                _currentPaletteHash = palette.GetHashCode();
            }
        }
示例#8
0
        private static void TestBmpEncoderCore <TPixel>(TestImageProvider <TPixel> provider, BmpBitsPerPixel bitsPerPixel)
            where TPixel : struct, IPixel <TPixel>
        {
            using (Image <TPixel> image = provider.GetImage())
            {
                // there is no alpha in bmp!
                image.Mutate(c => c.MakeOpaque());

                var encoder = new BmpEncoder {
                    BitsPerPixel = bitsPerPixel
                };

                // Does DebugSave & load reference CompareToReferenceInput():
                image.VerifyEncoder(provider, "bmp", bitsPerPixel, encoder);
            }
        }
示例#9
0
        public byte[] ResizeImage(byte[] imageBytes, int width, int height)
        {
            using (var image = Image.Load(imageBytes, out IImageFormat imageFormat))
                using (var outStream = new MemoryStream())
                {
                    if (width == 0)
                    {
                        width = image.Width;
                    }
                    if (height == 0)
                    {
                        height = image.Height;
                    }
                    image.Mutate(x => x
                                 .Resize(new ResizeOptions()
                    {
                        Size = new Size(width, height),
                        Mode = ResizeMode.Pad
                    })
                                 .BackgroundColor(Rgba32.White));

                    IImageEncoder encoder = null;
                    switch (imageFormat.Name)
                    {
                    case "PNG":
                        encoder = new PngEncoder();
                        break;

                    case "GIF":
                        encoder = new GifEncoder();
                        break;

                    case "BMP":
                        encoder = new BmpEncoder();
                        break;

                    default:
                        encoder = new JpegEncoder();
                        break;
                    }

                    image.Save(outStream, encoder);
                    return(outStream.ToArray());
                }
        }
示例#10
0
        private static void AddFrame(IcoFrame frame, ParseContext context, CommandLineOptions opts)
        {
            var outputEncoding = GetOutputEncoding(frame, opts);
            var extension      = outputEncoding == IcoEncodingType.Bitmap ? "bmp" : "png";
            var outputFilename = $"{context.FullPath}.{context.ImageDirectoryIndex:D2}.{frame.Encoding.ActualWidth}x{frame.Encoding.ActualHeight}x{frame.Encoding.ActualBitDepth}.{extension}";

            if (File.Exists(outputFilename) && opts.ForceOverwrite == false)
            {
                Reporter.WarnLine(IcoErrorCode.FileExists, $"Not overwriting existing file {outputFilename}.  Use --force-overwrite to change behavior.");
                return;
            }

            Reporter.VerboseLine($"Writing frame to {outputFilename}...");

            switch (outputEncoding)
            {
            case IcoEncodingType.Bitmap:
                var bitmap = BmpEncoder.EncodeBitmap(context, frame.Encoding.PixelFormat, BmpEncoder.Dialect.Bmp, frame);
                File.WriteAllBytes(outputFilename, bitmap);
                break;

            case IcoEncodingType.Png:
                if (frame.Encoding.Type == IcoEncodingType.Png)
                {
                    File.WriteAllBytes(outputFilename, frame.RawData);
                }
                else
                {
                    using (var stream = new MemoryStream())
                    {
                        frame.CookedData.SaveAsPng(stream, context.PngEncoder);

                        stream.Flush();
                        var png = stream.GetBuffer();
                        File.WriteAllBytes(outputFilename, stream.GetBuffer());
                    }
                }
                break;
            }
        }
示例#11
0
        private void SaveCircuitBoard(string path)
        {
            string extension = Path.GetExtension(path).ToLowerInvariant();

            IImageEncoder encoder;

            switch (extension)
            {
            case ".png":
                encoder = new PngEncoder
                {
                    ColorType = PngColorType.RgbWithAlpha,
                };
                break;

            case ".bmp":
                encoder = new BmpEncoder
                {
                    BitsPerPixel        = BmpBitsPerPixel.Pixel32,
                    SupportTransparency = true
                };
                break;

            case ".tga":
                encoder = new TgaEncoder
                {
                    BitsPerPixel = TgaBitsPerPixel.Pixel32
                };
                break;

            default:
                throw new NotSupportedException($"No image encoder available for file extension \"{extension}\".");
            }

            using (Image <Bgra32> image = circuitBoard.ToImage().ToImageSharp())
            {
                image.Save(path, encoder);
            }
        }
示例#12
0
        public void Encode_PreserveBitsPerPixel(string imagePath, BmpBitsPerPixel bmpBitsPerPixel)
        {
            var options = new BmpEncoder();

            var testFile = TestFile.Create(imagePath);

            using (Image <Rgba32> input = testFile.CreateRgba32Image())
            {
                using (var memStream = new MemoryStream())
                {
                    input.Save(memStream, options);

                    memStream.Position = 0;
                    using (var output = Image.Load <Rgba32>(memStream))
                    {
                        BmpMetadata meta = output.Metadata.GetBmpMetadata();

                        Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel);
                    }
                }
            }
        }
示例#13
0
        static void Process(byte[] buffer, BmpEncoder encoder, out byte[] palette, out short width, out short height, out byte[] bitmap)
        {
            using (Image image = ImageProcessor.ProcessImage(buffer, out IImageFormat mime))
            {
                width  = (short)image.Width;
                height = (short)image.Height;

                using (var stream = new MemoryStream())
                {
                    if (mime.DefaultMimeType != BmpFormat.Instance.DefaultMimeType)
                    {
                        image.Mutate(x => x.Flip(FlipMode.Vertical)); // Resolves the BMP inverse pixel order.
                    }
                    image.Save(stream, encoder);

                    using (var reader = new BinaryReader(stream))
                    {
                        reader.BaseStream.Position = BMP_HEADER_PALETTE_COLORS_OFFSET;
                        int colors        = reader.ReadInt32(); // 0 means the default 256 colors.
                        int paletteLength = (colors != 0 ? colors : RGB_PALETTE_LENGTH) * 4;

                        if (encoder == DefaultEncoder)
                        {
                            reader.BaseStream.Position = BMP_HEADER_LENGTH;
                            byte[] colorTable = reader.ReadBytes(paletteLength);
                            palette = ExtractPalette(colorTable);
                        }
                        else
                        {
                            palette = null;
                            reader.BaseStream.Position = BMP_HEADER_LENGTH + paletteLength;
                        }

                        bitmap = reader.ReadBytes(width * height);
                    }
                }
            }
        }
示例#14
0
        public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
        {
            var options = new BmpEncoder();

            var testFile = TestFile.Create(imagePath);

            using (Image <Rgba32> input = testFile.CreateRgba32Image())
            {
                using (var memStream = new MemoryStream())
                {
                    input.Save(memStream, options);

                    memStream.Position = 0;
                    using (var output = Image.Load <Rgba32>(memStream))
                    {
                        ImageMetadata meta = output.Metadata;
                        Assert.Equal(xResolution, meta.HorizontalResolution);
                        Assert.Equal(yResolution, meta.VerticalResolution);
                        Assert.Equal(resolutionUnit, meta.ResolutionUnits);
                    }
                }
            }
        }
示例#15
0
 /// <summary>
 /// Saves the image to the given stream with the bmp format.
 /// </summary>
 /// <typeparam name="TPixel">The pixel format.</typeparam>
 /// <param name="source">The image this method extends.</param>
 /// <param name="stream">The stream to save the image to.</param>
 /// <param name="encoder">The encoder to save the image with.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the stream is null.</exception>
 public static void SaveAsBmp <TPixel>(this Image <TPixel> source, Stream stream, BmpEncoder encoder)
     where TPixel : struct, IPixel <TPixel>
 => source.Save(stream, encoder ?? source.GetConfiguration().FindEncoder(ImageFormats.Bmp));
示例#16
0
 /// <summary>
 /// Saves the image to the given stream with the bmp format.
 /// </summary>
 /// <param name="source">The image this method extends.</param>
 /// <param name="path">The file path to save the image to.</param>
 /// <param name="encoder">The encoder to save the image with.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the path is null.</exception>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 public static Task SaveAsBmpAsync(this Image source, string path, BmpEncoder encoder) =>
 source.SaveAsync(
     path,
     encoder ?? source.GetConfiguration().ImageFormatsManager.FindEncoder(BmpFormat.Instance));
 /// <summary>
 /// Saves the image to the given stream with the Bmp format.
 /// </summary>
 /// <param name="source">The image this method extends.</param>
 /// <param name="stream">The stream to save the image to.</param>
 /// <param name="encoder">The encoder to save the image with.</param>
 /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the stream is null.</exception>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 public static Task SaveAsBmpAsync(this Image source, Stream stream, BmpEncoder encoder, CancellationToken cancellationToken = default) =>
 source.SaveAsync(
     stream,
     encoder ?? source.GetConfiguration().ImageFormatsManager.FindEncoder(BmpFormat.Instance),
     cancellationToken);
示例#18
0
        private static void EmitAllPossibleEncodings(ParseContext context, IcoFrame source)
        {
            byte[] png;

            var pathPrefix = $"{context.FullPath}.{context.ImageDirectoryIndex:D2}.";

            using (var stream = new MemoryStream())
            {
                source.CookedData.SaveAsPng(stream, context.PngEncoder);

                stream.Flush();
                png = stream.GetBuffer();
                var pngPath = $"{pathPrefix}png";
                File.WriteAllBytes(pngPath, stream.GetBuffer());
            }

            var bitmap1 = BmpEncoder.EncodeBitmap(context, BitmapEncoding.Pixel_indexed1, BmpEncoder.Dialect.Bmp, source);

            if (bitmap1 != null)
            {
                var bmp1Path = $"{pathPrefix}01bpp.bmp";
                File.WriteAllBytes(bmp1Path, bitmap1);
            }

            var bitmap4 = BmpEncoder.EncodeBitmap(context, BitmapEncoding.Pixel_indexed4, BmpEncoder.Dialect.Bmp, source);

            if (bitmap4 != null)
            {
                var bmp4Path = $"{pathPrefix}04bpp.bmp";
                File.WriteAllBytes(bmp4Path, bitmap4);
            }

            var bitmap8 = BmpEncoder.EncodeBitmap(context, BitmapEncoding.Pixel_indexed8, BmpEncoder.Dialect.Bmp, source);

            if (bitmap8 != null)
            {
                var bmp8Path = $"{pathPrefix}08bpp.bmp";
                File.WriteAllBytes(bmp8Path, bitmap8);
            }

            var bitmap16 = BmpEncoder.EncodeBitmap(context, BitmapEncoding.Pixel_rgb15, BmpEncoder.Dialect.Bmp, source);

            if (bitmap16 != null)
            {
                var bmp16Path = $"{pathPrefix}16bpp.bmp";
                File.WriteAllBytes(bmp16Path, bitmap16);
            }

            var bitmap32 = BmpEncoder.EncodeBitmap(context, BitmapEncoding.Pixel_0rgb32, BmpEncoder.Dialect.Bmp, source);

            if (bitmap32 != null)
            {
                var bmp32Path = $"{pathPrefix}32bpp0.bmp";
                File.WriteAllBytes(bmp32Path, bitmap32);
            }

            var bitmap32a = BmpEncoder.EncodeBitmap(context, BitmapEncoding.Pixel_argb32, BmpEncoder.Dialect.Bmp, source);

            if (bitmap32a != null)
            {
                var bmp32Path = $"{pathPrefix}32Abpp.bmp";
                File.WriteAllBytes(bmp32Path, bitmap32a);
            }
        }
        //returns an encoder based on image type
        public static ImageEncoder GetEncoderFromType(ImageType type)
        {
            ImageEncoder encoder = null;

            switch (type)
            {
            case ImageType.Jpeg:
                encoder = new JpegEncoder();
                break;

            case ImageType.Png:
                encoder = new PngEncoder();
                break;

            case ImageType.J2k:
                encoder = new Jp2Encoder();
                break;

            case ImageType.Bmp:
                encoder = new BmpEncoder();
                break;

            case ImageType.Emf:
                encoder = new EmfEncoder();
                break;

            case ImageType.Gif:
                encoder = new GifEncoder();
                break;

            case ImageType.Pcx:
                encoder = new PcxEncoder();
                break;

            case ImageType.Psd:
                encoder = new PsdEncoder();
                break;

            case ImageType.Tga:
                encoder = new TgaEncoder();
                break;

            case ImageType.Tiff:
                encoder = new TiffEncoder();
                break;

            case ImageType.Wbmp:
                encoder = new WbmpEncoder();
                break;

            case ImageType.Wmf:
                encoder = new WmfEncoder();
                break;

            case ImageType.Tla:
                encoder = new TlaEncoder();
                break;

            default:
                MessageBox.Show("当前的图像格式不支持");
                break;
            }

            return(encoder);
        }
        //returns an encoder based on image type
        public static ImageEncoder GetEncoderFromType( ImageType type )
        {
            ImageEncoder encoder = null;
            switch ( type )
            {
                case ImageType.Jpeg:
                    encoder = new JpegEncoder();
                    break;
                case ImageType.Png:
                    encoder = new PngEncoder();
                    break;
				case ImageType.J2k:
					encoder = new Jp2Encoder();
					break;
                case ImageType.Bmp:
                    encoder = new BmpEncoder();
                    break;
                case ImageType.Emf:
                    encoder = new EmfEncoder();
                    break;
                case ImageType.Gif:
                    encoder = new GifEncoder();
                    break;
                case ImageType.Pcx:
                    encoder = new PcxEncoder();
                    break;
                case ImageType.Psd:
                    encoder = new PsdEncoder();
                    break;
                case ImageType.Tga:
                    encoder = new TgaEncoder();
                    break;
                case ImageType.Tiff:
                    encoder = new TiffEncoder();
                    break;
                case ImageType.Wbmp:
                    encoder = new WbmpEncoder();
                    break;
                case ImageType.Wmf:
                    encoder = new WmfEncoder();
                    break;
                case ImageType.Tla:
                    encoder = new TlaEncoder();
                    break;
                default:
                    MessageBox.Show( "当前的图像格式不支持" );
                    break;
            }

            return encoder;
        } 
        /// <summary>
        /// Shows the encoder settings dialog and initializes the encoder.
        /// </summary>
        /// <param name="encoder">The encoder.</param>
        /// <param name="canAddImagesToExistingFile">The value indicating whether encoder can add images to the existing multipage image file.</param>
        /// <returns>
        /// <b>True</b> if settings are applied to the encoder; otherwise, <b>false</b>.
        /// </returns>
        protected virtual bool ShowEncoderSettingsDialog(
            ref EncoderBase encoder,
            bool canAddImagesToExistingFile)
        {
            // set encoder settings
            switch (encoder.Name)
            {
            case "Bmp":
                using (BmpEncoderSettingsForm bmpEncoderSettingsForm = new BmpEncoderSettingsForm())
                {
                    SetEncoderSettingsDialogProperties(bmpEncoderSettingsForm);
                    if (bmpEncoderSettingsForm.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    BmpEncoder bmpEncoder = (BmpEncoder)encoder;

                    bmpEncoder.Settings = bmpEncoderSettingsForm.EncoderSettings;
                    return(true);
                }

            case "Png":
                using (PngEncoderSettingsForm pngEncoderSettingsForm = new PngEncoderSettingsForm())
                {
                    SetEncoderSettingsDialogProperties(pngEncoderSettingsForm);
                    if (pngEncoderSettingsForm.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    PngEncoder pngEncoder = (PngEncoder)encoder;

                    pngEncoder.Settings = pngEncoderSettingsForm.EncoderSettings;
                    return(true);
                }

            case "Gif":
                using (GifEncoderSettingsForm gifEncoderSettingsForm = new GifEncoderSettingsForm())
                {
                    SetEncoderSettingsDialogProperties(gifEncoderSettingsForm);
                    gifEncoderSettingsForm.CanAddImagesToExistingFile = canAddImagesToExistingFile;
                    if (gifEncoderSettingsForm.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    GifEncoder gifEncoder = (GifEncoder)encoder;

                    gifEncoder.Settings      = gifEncoderSettingsForm.EncoderSettings;
                    gifEncoder.CreateNewFile = !gifEncoderSettingsForm.AddImagesToExistingFile;
                    return(true);
                }

            case "Jpeg":
                using (JpegEncoderSettingsForm jpegEncoderSettingsForm = new JpegEncoderSettingsForm())
                {
                    SetEncoderSettingsDialogProperties(jpegEncoderSettingsForm);
                    if (jpegEncoderSettingsForm.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    JpegEncoder jpegEncoder = (JpegEncoder)encoder;

                    jpegEncoder.Settings = jpegEncoderSettingsForm.EncoderSettings;
                    return(true);
                }

            case "Tiff":
                using (TiffEncoderSettingsForm tiffEncoderSettingsForm = new TiffEncoderSettingsForm())
                {
                    SetEncoderSettingsDialogProperties(tiffEncoderSettingsForm);
                    tiffEncoderSettingsForm.CanAddImagesToExistingFile = canAddImagesToExistingFile;
                    if (tiffEncoderSettingsForm.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    TiffEncoder tiffEncoder = (TiffEncoder)encoder;

                    tiffEncoder.Settings      = tiffEncoderSettingsForm.EncoderSettings;
                    tiffEncoder.CreateNewFile = !tiffEncoderSettingsForm.AddImagesToExistingFile;
                    return(true);
                }

            case "Svg":
                using (SvgEncoderSettingsForm svgEncoderSettingsForm = new SvgEncoderSettingsForm())
                {
                    SetEncoderSettingsDialogProperties(svgEncoderSettingsForm);
                    if (svgEncoderSettingsForm.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    SvgEncoder svgEncoder = (SvgEncoder)encoder;

                    svgEncoder.Settings = svgEncoderSettingsForm.EncoderSettings;
                    return(true);
                }
            }

            return(false);
        }
示例#22
0
 /// <summary>
 /// Saves the image to the given stream with the bmp format.
 /// </summary>
 /// <param name="source">The image this method extends.</param>
 /// <param name="stream">The stream to save the image to.</param>
 /// <param name="encoder">The encoder to save the image with.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the stream is null.</exception>
 public static void SaveAsBmp(this Image source, Stream stream, BmpEncoder encoder) =>
 source.Save(
     stream,
     encoder ?? source.GetConfiguration().ImageFormatsManager.FindEncoder(BmpFormat.Instance));
示例#23
0
        private static IcoFrame GetBestEncodingForFrame(ParseContext context, CommandLineOptions opts, IcoFrame source)
        {
            var result = new IcoFrameEncoding
            {
                ClaimedBitDepth = source.Encoding.ClaimedBitDepth,
                ClaimedHeight   = source.Encoding.ClaimedHeight,
                ClaimedWidth    = source.Encoding.ClaimedWidth,
                ActualHeight    = (uint)source.CookedData.Height,
                ActualWidth     = (uint)source.CookedData.Width,
            };

            byte[] png    = null;
            byte[] bitmap = null;

            var policy = opts.BestFormatPolicy;

            if (policy == BestFormatPolicy.Inherited)
            {
                policy = BestFormatPolicy.PreserveSource;
            }

            if (source.Encoding.ClaimedHeight == 16 &&
                source.Encoding.ClaimedWidth == 16 &&
                source.Encoding.ClaimedBitDepth == 32 &&
                opts.BestFormatPolicy16x16x32 != BestFormatPolicy.Inherited)
            {
                policy = opts.BestFormatPolicy16x16x32;
            }

            if (source.Encoding.ClaimedHeight == 32 &&
                source.Encoding.ClaimedWidth == 32 &&
                source.Encoding.ClaimedBitDepth == 32 &&
                opts.BestFormatPolicy32x32x32 != BestFormatPolicy.Inherited)
            {
                policy = opts.BestFormatPolicy32x32x32;
            }

            if (policy != BestFormatPolicy.AlwaysBmp &&
                (source.Encoding.ClaimedBitDepth == 32 || opts.BestFormatPolicy == BestFormatPolicy.AlwaysPng))
            {
                png = EncodePng(source, context);

                if (opts.PngToolPath != null)
                {
                    png = ReprocessPngFile(png, context, opts);
                }
            }

            if (opts.BestFormatPolicy != BestFormatPolicy.AlwaysPng)
            {
                foreach (var encoding in _allEncodings)
                {
                    if (encoding == BitmapEncoding.Pixel_indexed2)
                    {
                        switch (opts.Emit2BitBitmaps)
                        {
                        case StrictnessPolicy.Compliant:
                            continue;

                        case StrictnessPolicy.PreserveSource:
                            if (source.Encoding.PixelFormat != BitmapEncoding.Pixel_indexed2)
                            {
                                continue;
                            }

                            break;

                        case StrictnessPolicy.Loose:
                            break;
                        }
                    }

                    if (encoding == BitmapEncoding.Pixel_rgb24)
                    {
                        switch (opts.Emit24BitBitmaps)
                        {
                        case StrictnessPolicy.Compliant:
                            continue;

                        case StrictnessPolicy.PreserveSource:
                            if (source.Encoding.PixelFormat != BitmapEncoding.Pixel_rgb24)
                            {
                                continue;
                            }

                            break;

                        case StrictnessPolicy.Loose:
                            break;
                        }
                    }

                    if (source.Encoding.PixelFormat != encoding)
                    {
                        if (!opts.AllowDownsample)
                        {
                            continue;
                        }

                        // Going to rgb15 can lose some color data, due to rounding.  Avoid unless the source
                        // was already in rgb15.
                        if (encoding == BitmapEncoding.Pixel_rgb15)
                        {
                            continue;
                        }

                        // Don't lose the per-pixel alpha channel, if one was in the source.
                        if (source.Encoding.PixelFormat == BitmapEncoding.Pixel_argb32 && BmpUtil.IsAlphaSignificant(source))
                        {
                            continue;
                        }
                    }

                    bitmap = BmpEncoder.EncodeBitmap(context, encoding, BmpEncoder.Dialect.Ico, source);
                    if (bitmap != null)
                    {
                        result.PixelFormat = encoding;
                        break;
                    }
                }
            }

            switch (opts.BestFormatPolicy)
            {
            case BestFormatPolicy.PreserveSource:
                result.Type = source.Encoding.Type;
                break;

            case BestFormatPolicy.MinimizeStorage:
                result.Type = (bitmap.Length < ((png?.Length ?? 0) + opts.PngSizePenalty))
                        ? IcoEncodingType.Bitmap
                        : IcoEncodingType.Png;
                break;

            case BestFormatPolicy.PngLargeImages:
                result.Type = (source.CookedData.Width >= opts.LargeImagePixelThreshold)
                        ? IcoEncodingType.Png
                        : IcoEncodingType.Bitmap;
                break;

            case BestFormatPolicy.AlwaysPng:
                result.Type = IcoEncodingType.Png;
                break;

            case BestFormatPolicy.AlwaysBmp:
                result.Type = IcoEncodingType.Bitmap;
                break;

            default:
                break;
            }

            if (png == null && result.Type == IcoEncodingType.Png)
            {
                result.Type = IcoEncodingType.Bitmap;
            }

            var finalData = (result.Type == IcoEncodingType.Bitmap) ? bitmap : png;

            return(new IcoFrame {
                Encoding = result, RawData = finalData
            });
        }