简体   繁体   English

Javascript:检测文件阅读器中是否有图像

[英]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. 您可以再检查几个字节,以使结果具有较高的准确性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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