如何使用C#识别CMYK图像

20

有人知道如何使用 C# 正确识别 CMYK 图像吗?我找到了使用 ImageMagick 的方法,但我需要一个 .NET 解决方案。我在线上找到了 3 个代码片段,只有一个可以在 Windows 7 上工作,但全部都无法在 Windows Server 2008 SP2 上运行。我需要至少能够在 Windows Server 2008 SP2 上运行。下面是我找到的内容:


    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Drawing;
    using System.Drawing.Imaging;

    bool isCmyk;

    // WPF
    BitmapImage wpfImage = new BitmapImage(new Uri(imgFile));

    // false in Win7 & WinServer08, wpfImage.Format = Bgr32
    isCmyk = (wpfImage.Format == PixelFormats.Cmyk32);

    // Using GDI+
    Image img = Image.FromFile(file);

    // false in Win7 & WinServer08
    isCmyk = ((((ImageFlags)img.Flags) & ImageFlags.ColorSpaceCmyk) == 
        ImageFlags.ColorSpaceCmyk); 

    // true in Win7, false in WinServer08 (img.PixelFormat = Format24bppRgb) 
    isCmyk = ((int)img.PixelFormat) == 8207; 

你的两个测试盒子都是x86还是x64? - Steve Danner
两台机器都是64位的。可能是GDI+ dll的问题吗? - Alex Gil
img.PixelFormat 在两个操作系统中返回什么?wpfImage.Format 呢? - Gabe
1
啊... GDI+。这个库是.NET既完全依赖又完全害怕的。你会从System.Drawing对GDI+的依赖中得到更多的奇怪问题,如“内存不足”错误和无法解释的异常,比.NET框架中的任何其他东西都要多... - Dylan Beattie
Gabe,我修改了代码片段以显示wpfImage和img.PixelFormat返回的内容。 - Alex Gil
3个回答

6
我的测试结果与您的略有不同。
Windows 7: - ImageFlags: ColorSpaceRgb - PixelFormat: PixelFormat32bppCMYK (8207)
Windows Server 2008 R2: - ImageFlags: ColorSpaceRgb - PixelFormat: PixelFormat32bppCMYK (8207)
Windows Server 2008: - ImageFlags: ColorSpaceYcck - PixelFormat: Format24bppRgb
以下代码应该可以运行:
    public static bool IsCmyk(this Image image)
    {
        var flags = (ImageFlags)image.Flags;
        if (flags.HasFlag(ImageFlags.ColorSpaceCmyk) || flags.HasFlag(ImageFlags.ColorSpaceYcck))
        {
            return true;
        }

        const int PixelFormat32bppCMYK = (15 | (32 << 8));
        return (int)image.PixelFormat == PixelFormat32bppCMYK;
    }

5

我不建议使用BitmapImage作为加载数据的方式。事实上,我不会在这方面使用它。相反,我会使用BitmapDecoder::Create并传入BitmapCreateOptions.PreservePixelFormat。然后,您可以访问您感兴趣的BitmapFrame并检查其Format属性,现在应该产生CMYK。

然后,如果您确实需要显示图像,您只需将BitmapFrame(也是BitmapSource子类)分配给Image::Source即可。


0

我遇到了同样的问题,如果你使用的是 .net 2.0,那么 BitmapDecoder 将无法工作。你需要做的是读取文件并检查字节所表示的文件是否正确。如何使用 C# 在 ASP.NET 中识别 CMYK 图像 希望这能帮助到某些人。

祝好 - Jeremy


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接