在ImageMagick.NET中将颜色应用于PDF转换

cld4siwp  于 2023-03-31  发布在  .NET
关注(0)|答案(2)|浏览(148)

在延续从以前的SO后here我已经从能够从PDF转换中删除透明度,不能调整转换的背景颜色.我已经尝试了一切,我可以找到的Imagemagick.NET github docs .我需要确保通过这个软件包的任何图像有一个不透明的白色背景.

/// <summary>
    /// Write image data from a pdf file to a bitmap file
    /// </summary>
    /// <param name="imgData"></param>
    private static void convertPdfToBmp(ImageData imgData)
    {
        MagickReadSettings settings = new MagickReadSettings();
        // Settings the density to 600 dpi will create an image with a better quality
        settings.Density = new Density(600);

        using (MagickImageCollection images = new MagickImageCollection())
        {
            // Add all the pages of the pdf file to the collection
            images.Read(imgData.pdfFilePath, settings);

            // Create new image that appends all the pages horizontally
            using (IMagickImage image = images.AppendVertically())
            {
                // Remove the transparency layers and color the background white
                image.Alpha(AlphaOption.Remove);

                int aval = image.Settings.BackgroundColor.A = 0;
                int rval = image.Settings.BackgroundColor.R = 0;
                int bval = image.Settings.BackgroundColor.G = 0;
                int gval = image.Settings.BackgroundColor.B = 0;

                // Convert the image to a bitmap
                image.Format = MagickFormat.Bmp;

                // Delete any old file 
                if (File.Exists(imgData.bmpFilePath))
                {
                    File.Delete(imgData.bmpFilePath);
                }
                // Save result as a bmp
                image.Write(imgData.bmpFilePath);
            }
        }
    }

在上面的代码中,如果我将4个通道image.Settings.BackgroundColor中的任何一个设置为不同的颜色,它对图像没有影响。如果我使用image.BackgroundColor,它对图像没有影响。我遗漏了什么?
注意:在上面的代码中,我将颜色设置为黑色,以验证代码是否正常工作。我也尝试了其他颜色。

nbysray5

nbysray51#

从以下位置更改设置:

settings.Density = new Density(600);

到,

settings.Density = new Density(600);
settings.ColorType = ColorType.TrueColor;
settings.BackgroundColor = new MagickColor(Color.White);

我已经试过这个了,效果很完美。

mnemlml8

mnemlml82#

我在将PDF文件转换为一组图像时遇到了类似的问题。对我来说,解决的问题是不使用设置对象(除了密度),而是将所需的属性(格式,背景颜色,颜色类型)应用于图像。

magickReadSettings = new MagickReadSettings();
magickReadSettings.Density = new Density(300);

using (var images = new MagickImageCollection())
{
    // Add all the pages of the pdf file to the collection
    await images.ReadAsync(pdf, magickReadSettings);

    foreach (IMagickImage<ushort> image in images)
    {
        image.Format = MagickFormat.Png;
        image.BackgroundColor = new MagickColor(255, 255, 255, 255);
        image.ColorType = ColorType.Grayscale;
    }
}

相关问题