Exporting Images in .NET Standard
The .NET Standard specification does not define APIs for getting image properties. SpreadProcessing needs access to GDI+ basic graphics functionality when exporting spreadsheets that contain images. To allow the library to get the image properties needed for saving the workbook, set an implementation inheriting the ImagePropertiesResolverBase abstract class to the ImagePropertiesResolver property of SpreadExtensibilityManager.
The Telerik.Documents.ImageUtils package provides a default implementation of the
ImagePropertiesResolverclass that you can use when exporting the document.
Example 1: Set the default implementation of the ImagePropertiesResolver class
ImagePropertiesResolverBase imagePropertiesResolver = new ImagePropertiesResolver();
SpreadExtensibilityManager.ImagePropertiesResolver = imagePropertiesResolver;
Example 2: Create a custom implementation inheriting the ImagePropertiesResolverBase abstract class (Windows)
public class ImageInfo : ImagePropertiesResolverBase
{
public override Size GetImageSize(byte[] imageData)
{
Size size = Size.Empty;
try
{
using (SKBitmap decodedBitmap = SKBitmap.Decode(imageData))
{
size = new Size(decodedBitmap.Width, decodedBitmap.Height);
}
}
catch (Exception ex)
{
// Image format not recognized.
throw new NotSupportedException("Unsupported image format.", ex);
}
return size;
}
public override bool TryGetRawImageData(byte[] imageData, out byte[] rawRgbData, out byte[] rawAlpha, out Size size)
{
using (SKBitmap decodedBitmap = SKBitmap.Decode(imageData))
{
size = new Size(decodedBitmap.Width, decodedBitmap.Height);
GetRawDataFromRgbaSource(decodedBitmap, out rawRgbData, out rawAlpha);
return true;
}
}
private static void GetRawDataFromRgbaSource(SKBitmap decodedBitmap, out byte[] data, out byte[] alpha)
{
bool shouldExportAlpha = false;
List<byte> rawRgbData = new List<byte>(decodedBitmap.ByteCount / 4 * 3);
List<byte> rawAlpha = new List<byte>(decodedBitmap.ByteCount / 4);
SKColor[] pixels = decodedBitmap.Pixels;
for (int i = 0; i < pixels.Length; i++)
{
SKColor pixel = pixels[i];
byte r = pixel.Red;
byte g = pixel.Green;
byte b = pixel.Blue;
byte a = pixel.Alpha;
rawRgbData.Add(r);
rawRgbData.Add(g);
rawRgbData.Add(b);
rawAlpha.Add(a);
if (a != 255)
{
shouldExportAlpha = true;
}
}
data = rawRgbData.ToArray();
alpha = rawAlpha.ToArray();
if (!shouldExportAlpha)
{
alpha = null;
}
}
}
Example 3: Set the custom implementation inheriting the ImagePropertiesResolverBase abstract class
ImagePropertiesResolverBase imagePropertiesResolver = new ImageInfo();
SpreadExtensibilityManager.ImagePropertiesResolver = imagePropertiesResolver;