1

Is there a way to see if an image file is in the file reader in javascript?

0

1 Answer 1

2

You can try to determine if the file is an image by checking few bytes at the beginning of the stream. You can find the header signature of images easily by googling it.

This is a simple way to detect the image type:

 reader.onload = function(e) {
      var buffer = reader.result;
      var int32View = new Int32Array(buffer);
      switch(int32View[0]) {
          case 1196314761: 
              file.verified_type = "image/png";
              break;
          case 944130375:
              file.verified_type = "image/gif";
              break;
          case 544099650:
              file.verified_type = "image/bmp";
              break;
          case -520103681:
              file.verified_type = "image/jpg";
              break;
          default:
                            file.verified_type = "unknown";
              break;
      }
        }; 

You can check few more bytes to give high accuracy to your results.

Sign up to request clarification or add additional context in comments.

1 Comment

getting an empty int32View for any file type Int32Array [] ​ buffer: ArrayBuffer { byteLength: 0 } ​ byteLength: 0 ​ byteOffset: 0 ​ length: 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.