简体   繁体   中英

Javascript: Detect if there is an image in the file reader

有没有办法查看图像文件是否在javascript的文件读取器中?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM