Validate image from file in C#

Viewed 100730

I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.

string filePath = "image.jpg";
Image newImage = Image.FromFile(filePath);

The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.

I'm looking for a function that will validate an image given a stream or a file path of the image.

Example function prototype

bool IsValidImage(string fileName);
bool IsValidImage(Stream imageStream);
14 Answers

Using Windows Forms:

bool IsValidImage(string filename)
{
    try
    {
        using(Image newImage = Image.FromFile(filename))
        {}
    }
    catch (OutOfMemoryException ex)
    {
        //The file does not have a valid image format.
        //-or- GDI+ does not support the pixel format of the file

        return false;
    }
    return true;
}

Otherwise if you're using WPF you can do the following:

bool IsValidImage(string filename)
{
    try
    {
        using(BitmapImage newImage = new BitmapImage(filename))
        {}
    }
    catch(NotSupportedException)
    {
        // System.NotSupportedException:
        // No imaging component suitable to complete this operation was found.
        return false;
    }
    return true;
}

You must release the image created. Otherwise when you call this function large number of times, this would throw OutOfMemoryException because the system ran out of resources, and not because the image is corrupt yielding an incorrect result, and if you delete images after this step, you'd potentially be deleting good ones.

JPEG's don't have a formal header definition, but they do have a small amount of metadata you can use.

  • Offset 0 (Two Bytes): JPEG SOI marker (FFD8 hex)
  • Offset 2 (Two Bytes): Image width in pixels
  • Offset 4 (Two Bytes): Image height in pixels
  • Offset 6 (Byte): Number of components (1 = grayscale, 3 = RGB)

There are a couple other things after that, but those aren't important.

You can open the file using a binary stream, and read this initial data, and make sure that OffSet 0 is 0, and OffSet 6 is either 1,2 or 3.

That would at least give you slightly more precision.

Or you can just trap the exception and move on, but I thought you wanted a challenge :)

Well, I went ahead and coded a set of functions to solve the problem. It checks the header first, then attempts to load the image in a try/catch block. It only checks for GIF, BMP, JPG, and PNG files. You can easily add more types by adding a header to imageHeaders.

static bool IsValidImage(string filePath)
{
    return File.Exists(filePath) && IsValidImage(new FileStream(filePath, FileMode.Open, FileAccess.Read));
}

static bool IsValidImage(Stream imageStream)
{
    if(imageStream.Length > 0)
    {
        byte[] header = new byte[4]; // Change size if needed.
        string[] imageHeaders = new[]{
                "\xFF\xD8", // JPEG
                "BM",       // BMP
                "GIF",      // GIF
                Encoding.ASCII.GetString(new byte[]{137, 80, 78, 71})}; // PNG

        imageStream.Read(header, 0, header.Length);

        bool isImageHeader = imageHeaders.Count(str => Encoding.ASCII.GetString(header).StartsWith(str)) > 0;
        if (isImageHeader == true)
        {
            try
            {
                Image.FromStream(imageStream).Dispose();
                imageStream.Close();
                return true;
            }

            catch
            {

            }
        }
    }

    imageStream.Close();
    return false;
}

You can do a rough typing by sniffing the header.

This means that each file format you implement will need to have a identifiable header...

JPEG: First 4 bytes are FF D8 FF E0 (actually just the first two bytes would do it for non jfif jpeg, more info here).

GIF: First 6 bytes are either "GIF87a" or "GIF89a" (more info here)

PNG: First 8 bytes are: 89 50 4E 47 0D 0A 1A 0A (more info here)

TIFF: First 4 bytes are: II42 or MM42 (more info here)

etc... you can find header/format information for just about any graphics format you care about and add to the things it handles as needed. What this won't do, is tell you if the file is a valid version of that type, but it will give you a hint about "image not image?". It could still be a corrupt or incomplete image, and thus crash when opening, so a try catch around the .FromFile call is still needed.

2019 here, dotnet core 3.1. I take the answer of Alex and actualise it a little

public static bool IsImage(this byte[] fileBytes)
{
    var headers = new List<byte[]>
    {
        Encoding.ASCII.GetBytes("BM"),      // BMP
        Encoding.ASCII.GetBytes("GIF"),     // GIF
        new byte[] { 137, 80, 78, 71 },     // PNG
        new byte[] { 73, 73, 42 },          // TIFF
        new byte[] { 77, 77, 42 },          // TIFF
        new byte[] { 255, 216, 255, 224 },  // JPEG
        new byte[] { 255, 216, 255, 225 }   // JPEG CANON
    };

    return headers.Any(x => x.SequenceEqual(fileBytes.Take(x.Length)));
}

Usage :

public async Task UploadImage(Stream file)
{
    using (MemoryStream ms = new MemoryStream())
    {
        await file.CopyToAsync(ms);

        byte[] bytes = ms.ToArray();

        if (!bytes.IsImage())
            throw new ArgumentException("Not an image", nameof(file));

        // Upload your file
    }
}

A method that supports Tiff and Jpeg also

private bool IsValidImage(string filename)
{
    Stream imageStream = null;
    try
    {
        imageStream = new FileStream(filename, FileMode.Open);

        if (imageStream.Length > 0)
        {
            byte[] header = new byte[30]; // Change size if needed.
            string[] imageHeaders = new[]
            {
                "BM",       // BMP
                "GIF",      // GIF
                Encoding.ASCII.GetString(new byte[]{137, 80, 78, 71}),// PNG
                "MM\x00\x2a", // TIFF
                "II\x2a\x00" // TIFF
            };

            imageStream.Read(header, 0, header.Length);

            bool isImageHeader = imageHeaders.Count(str => Encoding.ASCII.GetString(header).StartsWith(str)) > 0;
            if (imageStream != null)
            {
                imageStream.Close();
                imageStream.Dispose();
                imageStream = null;
            }

            if (isImageHeader == false)
            {
                //Verify if is jpeg
                using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
                {
                    UInt16 soi = br.ReadUInt16();  // Start of Image (SOI) marker (FFD8)
                    UInt16 jfif = br.ReadUInt16(); // JFIF marker

                    return soi == 0xd8ff && (jfif == 0xe0ff || jfif == 57855);
                }
            }

            return isImageHeader;
        }

        return false;
    }
    catch { return false; }
    finally
    {
        if (imageStream != null)
        {
            imageStream.Close();
            imageStream.Dispose();
        }
    }
}

I would create a method like:

Image openImage(string filename);

in which I handle the exception. If the returned value is Null, there is an invalid file name / type.

You could read the first few bytes of the Stream and compare them to the magic header bytes for JPEG.

Here is my approch using multiple validations.

public class ImageValidator
{
    private readonly Dictionary<string,byte[]> _validBytes = new Dictionary<string, byte[]>() {
        { ".bmp", new byte[] { 66, 77 } },
        { ".gif", new byte[] { 71, 73, 70, 56 } },
        { ".ico", new byte[] { 0, 0, 1, 0 } },
        { ".jpg", new byte[] { 255, 216, 255 } },
        { ".png", new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 } },
        { ".tiff", new byte[] { 73, 73, 42, 0 } },
    };

    /// <summary>
    /// image formats to validate using Guids from ImageFormat.
    /// </summary>
    private readonly Dictionary<Guid, string> _validGuids = new Dictionary<Guid, string>() {
        {ImageFormat.Jpeg.Guid, ".jpg" },
        {ImageFormat.Png.Guid, ".png"},
        {ImageFormat.Bmp.Guid, ".bmp"},
        {ImageFormat.Gif.Guid, ".gif"},
        {ImageFormat.Tiff.Guid, ".tiff"},
        {ImageFormat.Icon.Guid, ".ico" }
    };

    /// <summary>
    /// Supported extensions: .jpg,.png,.bmp,.gif,.tiff,.ico
    /// </summary>
    /// <param name="allowedExtensions"></param>
    public ImageValidator(string allowedExtensions = ".jpg;.png")
    {
        var exts = allowedExtensions.Split(';');
        foreach (var pair in _validGuids.ToArray())
        {
            if (!exts.Contains(pair.Value))
            {
                _validGuids.Remove(pair.Key);
            }
        }

        foreach (var pair in _validBytes.ToArray())
        {
            if (!exts.Contains(pair.Key))
            {
                _validBytes.Remove(pair.Key);
            }
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0063:Use simple 'using' statement", Justification = "<Pending>")]
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>")]
    public async Task<bool> IsValidAsync(Stream imageStream, string filePath)
    {
        if(imageStream == null || imageStream.Length == 0)
        {
            return false;
        }

        //First validate using file extension
        string ext = Path.GetExtension(filePath).ToLower();
        if(!_validGuids.ContainsValue(ext))
        {
            return false;
        }

        //Check mimetype by content
        if(!await IsImageBySigAsync(imageStream, ext))
        {
            return false;
        }

        try
        {
            //Validate file using Guid.
            using (var image = Image.FromStream(imageStream))
            {
                imageStream.Position = 0;
                var imgGuid = image.RawFormat.Guid;
                if (!_validGuids.ContainsKey(imgGuid))
                {
                    return false;
                }

                var validExtension = _validGuids[imgGuid];
                if (validExtension != ext)
                {
                    return false;
                }
            }
        }
        catch (OutOfMemoryException)
        {
            return false;
        }

        return true;
    }

    /// <summary>
    /// Validate the mimetype using byte and file extension.
    /// </summary>
    /// <param name="imageStream"></param>
    /// <param name="extension"></param>
    /// <returns></returns>
    private async Task<bool> IsImageBySigAsync(Stream imageStream, string extension)
    {
        var length = _validBytes.Max(x => x.Value.Length);
        byte[] imgByte = new byte[length];
        await imageStream.ReadAsync(imgByte, 0, length);
        imageStream.Position = 0;

        if (_validBytes.ContainsKey(extension))
        {
            var validImgByte = _validBytes[extension];
            if (imgByte.Take(validImgByte.Length).SequenceEqual(validImgByte))
            {
                return true;
            }
        }

        return false;
    }
}

in case yo need that data read for other operations and/or for other filetypes (PSD for example), later on, then using the Image.FromStream function is not necessarily a good ideea.

Related