Search code examples
c#macos.net-coretiffbmp

Convert BMP to TIFF using System.Drawing.Common on Mac OS X


I'm trying to convert a BMP image to a tiff image using System.Drawing.Common with the following C# code (.NET CORE 3.1) on Mac os:

        public void SaveBitmapAsTiff(string location, Bitmap image)
        {

            var imageCodecInfo = GetEncoderInfo("image/tiff");
            var encoder = Encoder.Compression;
            var encoderParameters = new EncoderParameters(1);
            
            var encoderParameter = new EncoderParameter(
                encoder,
                (long)EncoderValue.CompressionLZW);
            encoderParameters.Param[0] = encoderParameter;
            location = location.Replace(".bmp", "");
            image.Save(location + ".tiff", imageCodecInfo, encoderParameters);
            // image.Save(location + ".tiff", ImageFormat.Tiff); Also tried this method overload
        }
        
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for(j = 0; j < encoders.Length; ++j)
            {
                if(encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

the location parameter contains the file path we want to write to, and the image parameter contains the bitmap we loaded from the disk.

When I try to run this code I get the following exception:

Unhandled exception. System.NotImplementedException: Not implemented.
   at System.Drawing.SafeNativeMethods.Gdip.CheckStatus(Int32 status)
   at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
   at System.Drawing.Image.Save(String filename, ImageFormat format)
   at BmpTiffConverter.Services.FileService.SaveBitmapAsTiff(String location, Bitmap image) in /Users/tomcoldenhoff/Documents/ReSoftware/Repositories/BmpTiffConverter/BmpTiffConverter/Services/FileService.cs:line 54
   at BmpTiffConverter.Services.ConverterService.ConvertBmpToTiff(String inputPath, String outputPath) in /Users/tomcoldenhoff/Documents/ReSoftware/Repositories/BmpTiffConverter/BmpTiffConverter/Services/ConverterService.cs:line 20

My google searches suggested that I had to install libgdiplus which I already did with brew install mono-libgdiplus and brew upgrade mono-libgdiplus.

I've also tried @Andy's suggested answer by installing the runtime.osx.10.10-x64.CoreCompat.System.Drawing package, unfortunately this didn't work.

Does anyone have another suggestion?


Solution

  • The issue is that mono-libgdiplus doesn't implement EncoderValue.CompressionLZW encoder parameter. I would suggest not using that library, and instead install this nuget package:

    mac os libgdiplus

    runtime.osx.10.10-x64.CoreCompat.System.Drawing

    Once I added that package, your code worked perfectly.