简体   繁体   中英

Loading Canon .CR2 files in .NET

I am trying to process Canon RAW .CR2 files using C#. My code is as follows:

BitmapDecoder bmpDec = BitmapDecoder.Create(new Uri(origFile), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
BitmapEncoder bmpEnc = new BmpBitmapEncoder();
bmpEnc.Frames.Add(bmpDec.Frames[0]);
Stream ms = new MemoryStream();
bmpEnc.Save(ms);
Image srcImage = Bitmap.FromStream(ms);

The first few lines seem to run without a hitch, but the line

bmEnc.Save(ms);

just hangs without completing and without raising any exception.

Has anyone had any success with this?

W8.1 or W7 after applying https://www.microsoft.com/en-us/download/details.aspx?id=26829 seems to work well

var files = Directory.GetFiles(@"D:\DCIM","*.CR2");
            for(var i = 0; i < files.Length; i++) {
                Console.Write("{0,-4}: {1} => ", i, files[i]);
                var bmpDec = BitmapDecoder.Create(new Uri(files[i]), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
                var bmpEnc = new JpegBitmapEncoder();
                bmpEnc.QualityLevel = 100;
                bmpEnc.Frames.Add(bmpDec.Frames[0]);
                var oldfn = Path.GetFileName(files[i]);
                var newfn = Path.ChangeExtension(oldfn, "JPG");
                using(var ms = File.Create(Path.Combine(@"D:\DCIM\100CANON", newfn), 10000000)) {
                    bmpEnc.Save(ms);
                }
                Console.WriteLine(newfn);
            }

Know this is a old thread but I found a nice easy to use library (Magick.NET).

How to do a conversion:

using (MagickImage image = new MagickImage("StillLife.CR2"))
{
    image.Write("StillLife.jpg");
}

https://github.com/dlemstra/Magick.NET/blob/master/docs/ReadRawImageFromCamera.md

Details of nuget package installation:

Install-Package Magick.NET-Q16-AnyCPU

https://github.com/dlemstra/Magick.NET

I don't believe BitmapDecoder understands .CR2. It is not a conventional image format by far, as it contains the raw bayer-sensor image (one color per pixel), not a standard image.

If you want to convert CR2 and other camera raw formats, you should look at DCRaw: http://www.cybercom.net/~dcoffin/dcraw/ or libraw (based on dcraw, friendly as a library): http://www.libraw.org/

NuGet package: Magick.NET-Q16-AnyCPU

    private void ConvertToJpg(string path, string saveToFolder)
    {
        var filename = Path.GetFileName(path);

        ImageFormat format = ImageFormat.Jpeg;

        using (MagickImage magImg = new MagickImage(path))
        {
            magImg.Format = MagickFormat.Jpg;
            magImg.Quality = 99;
            magImg.Write($"{saveToFolder}\\{filename}.jpg");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM