Create Custom JpegImageConverter in .Net Standard

Product Version Product Author
2020.2.513 RadPdfProcessing Martin Velikov

Description

.NET Standard specification does not define APIs for converting images or scaling their quality. That is why to export to PDF format a document containing images different than Jpeg and Jpeg2000 or ImageQuality different than High, you will need to provide an implementation of the JpegImageConverterBase abstract class. This implementation should be passed to the JpegImageConverter property of the of FixedExtensibilityManager.

Solution

The following code snippets demonstrates how to create a custom implementation of the JpegImageConverterBase abstract class using the SixLabors.ImageSharp library and set it to the JpegImageConverter property of the FixedExtensibilityManager. We are using the ImageSharp library to convert the images from one of the library`s supported formats to Jpeg and to change their quality if it is set.

__ Create a custom implementation inheriting the JpegImageConverterBase abstract class

internal class CustomJpegImageConverter : JpegImageConverterBase 
{ 
    public override bool TryConvertToJpegImageData(byte[] imageData, ImageQuality imageQuality, out byte[] jpegImageData) 
    { 
        string[] imageSharpImageFormats = new string[] { "jpeg", "bmp", "png", "gif" }; 
        string imageFormat; 
 
        if (this.TryGetImageFormat(imageData, out imageFormat) && imageSharpImageFormats.Contains(imageFormat.ToLower())) 
        { 
            using (Image imageSharp = Image.Load(imageData)) 
            { 
                imageSharp.Mutate(x => x.BackgroundColor(Color.White)); 
 
                JpegEncoder options = new JpegEncoder 
                { 
                    Quality = (int)imageQuality, 
                }; 
 
                MemoryStream ms = new MemoryStream(); 
                imageSharp.SaveAsJpeg(ms, options); 
 
                jpegImageData = ms.ToArray(); 
            } 
 
            return true; 
        } 
 
        jpegImageData = null; 
        return false; 
    } 
} 

__ Set the custom implementation to the JpegImageConverter property of the FixedExtensibilityManager

JpegImageConverterBase customJpegImageConverter = new CustomJpegImageConverter();  
FixedExtensibilityManager.JpegImageConverter = customJpegImageConverter;  
In this article
Not finding the help you need? Improve this article