Simple: check whether the image is
null
, and return a suitable default in that case. For example:
byte[] ConvertImageToBinary(Image img)
{
if (img is null) return Array.Empty<byte>();
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
}
If an empty byte array doesn't work, try a single-pixel transparent GIF:
graphics - smallest filesize for transparent single pixel image - Stack Overflow[
^]
if (img is null)
{
return new byte[]
{
0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x01, 0x00, 0xFF, 0xFF, 0xFF, 0x00,
0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01
};
}
(You should cache the default image byte array in a private static readonly field, so that you don't have to create a new array each time.)