Majid Safeer
Majid Safeer

Reputation: 41

How to find image type using image URL having a misleading file extension

The following URL contains a .WebP image but the extension type in URL is .Jpeg

https://imagizer.imageshack.com/img924/6277/G9iEx4.jpg

I want to write a code that detects the actual image type of this image.

Hint: If you open this URL in the browser and try to save then it will give the correct image type which is WebP

I have tried the following code but it is returning .Jpeg as a type which is wrong, it should return .WebP

string imageUrl = "https://imagizer.imageshack.com/img924/6277/G9iEx4.jpg";

                using (WebClient client = new WebClient())
                {
                    byte[] imageData = client.DownloadData(imageUrl);
                    string imageType = "";
                    if (imageData.Length >= 8) 
                    {
                        if (IsJPEG(imageData))
                            imageType = "JPEG";
                        if (IsWebP(imageData))
                            imageType = "WebP";
                    }
                }
 public static bool IsPNG(byte[] imageBytes)
        {
            return imageBytes[0] == 0x89 && imageBytes[1] == 0x50 && imageBytes[2] == 0x4E && imageBytes[3] == 0x47 &&
                   imageBytes[4] == 0x0D && imageBytes[5] == 0x0A && imageBytes[6] == 0x1A && imageBytes[7] == 0x0A;
        }
 public static bool IsWebP(byte[] imageBytes)
        {
            return imageBytes.Length >= 12 &&
                   imageBytes[0] == (byte)'R' && imageBytes[1] == (byte)'I' && imageBytes[2] == (byte)'F' &&
                   imageBytes[3] == (byte)'F' && imageBytes[8] == (byte)'W' && imageBytes[9] == (byte)'E' &&
                   imageBytes[10] == (byte)'B' && imageBytes[11] == (byte)'P';
        }

Upvotes: 1

Views: 72

Answers (0)

Related Questions