Create Custom JpegImageConverter in .Net Standard
Product Version | Product | Author |
---|---|---|
2023.1.315 | RadPdfProcessing | Martin Velikov |
2.1.6 | ImageSharp |
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 FixedExtensibilityManager.
Solution
The following code snippets demonstrate 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 JpegImageConverter : JpegImageConverterBase
{
public override bool TryConvertToJpegImageData(byte[] imageData, ImageQuality imageQuality, out byte[] jpegImageData)
{
try
{
IImageFormat imageFormat;
using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image.Load(imageData, out imageFormat))
{
if (imageFormat.GetType() == typeof(PngFormat))
{
image.Mutate(x => x.BackgroundColor(Color.White));
}
JpegEncoder options = new JpegEncoder
{
Quality = (int)imageQuality,
};
using (MemoryStream ms = new MemoryStream())
{
image.SaveAsJpeg(ms, options);
jpegImageData = ms.ToArray();
}
}
return true;
}
catch (Exception ex)
{
if (ex is UnknownImageFormatException || ex is ImageProcessingException)
{
jpegImageData = null;
return false;
}
else
{
throw ex;
}
}
}
}
Set the custom implementation to the JpegImageConverter property of the FixedExtensibilityManager
JpegImageConverterBase customJpegImageConverter = new CustomJpegImageConverter();
FixedExtensibilityManager.JpegImageConverter = customJpegImageConverter;