开发者

How to identify CMYK images using C#

Does anybody know how to properly identify CMYK images using C#? I found how to do it using ImageMagick, but I need a .NET solution. I found 3 code snippets online, only one works in Windows 7, but all fail in Windows Server 2008 SP2. I need it to work at least in Windows Server 2008 SP2. Here is what I've found:


    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); 

  开发者_StackOverflow中文版  // true in Win7, false in WinServer08 (img.PixelFormat = Format24bppRgb) 
    isCmyk = ((int)img.PixelFormat) == 8207; 


My test results are a bit different than yours.

  • Windows 7:
    • ImageFlags: ColorSpaceRgb
    • PixelFormat: PixelFormat32bppCMYK (8207)
  • Windows Server 2008 R2:
    • ImageFlags: ColorSpaceRgb
    • PixelFormat: PixelFormat32bppCMYK (8207)
  • Windows Server 2008:
    • ImageFlags: ColorSpaceYcck
    • PixelFormat: Format24bppRgb

The following code should work:

    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;
    }


I wouldn't start with BitmapImage as your way of loading the data. In fact, I wouldn't use it at all for this. Instead I would use BitmapDecoder::Create and pass in BitmapCreateOptions.PreservePixelFormat. Then you can access the BitmapFrame you're interested in and check its Format property which should now yield CMYK.

Then, if you really need to display the image, you can just assign the BitmapFrame, which is also a BitmapSource subclass, to an Image::Source.


I ran into the same issues and if your using .net 2.0 then BitmapDecoder will not work.. what you want to do is read the file and just plain check to see that what the bytes say the file is.. How to identify CMYK images in ASP.NET using C# Hope this helps someone.

Cheers - Jeremy

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜