【问题标题】:Check are the base64 images gzipped or not检查是否压缩了 base64 图像
【发布时间】:2016-10-04 16:54:51
【问题描述】:

我正在开发一个网络应用程序,流程是这样的:浏览器从服务器获取图像作为 base64 数据,然后 JavaScript 对这些图像进行编码等(作为网络服务器,我们使用带有 mod_deflate 模块的 apache ) 我想检查那些图像是否被压缩(gzipped)。

好吧,问题是 base64 图像没有 HTTP 标头,那么我该如何检查呢?任何想法?谢谢。

【问题讨论】:

  • “base64 图像没有 HTTP 标头”是什么意思?如果您收到响应,则有一些标题,它们应该告诉您正文是否已压缩,但我不确定您要的是什么。

标签: javascript apache http base64 mod-deflate


【解决方案1】:

如果您从服务器请求图像数据,响应将始终包含一些标头,如果内容被压缩(gzipped),您将看到标头content-encoding: gzip

但是,如果您想知道实际(base64 编码)数据是否被压缩(gzipped),您可以对 base64 字符串的前 4 个字符进行解码以获得至少前 2 个字节。如果前两个字节是1F 8B,则您正在处理压缩数据。

如果前 2 个字节是 50 4B,则它是压缩数据。 如果前 3 个字节是 FF D8 FF 它是 jpg/jpeg 数据。 如果前 4 个字节为 89 50 4E 47,则为 png 数据。

见:https://en.wikipedia.org/wiki/List_of_file_signatures

【讨论】:

    【解决方案2】:

    您正在从服务器获取 base64 格式的图像,因此现在解码 base64 格式的图像并将输出存储在变量中。现在让我们查看解码字符串并检查解码字符串的起始 10-12 个字符,因为文件扩展名存储在文件的开头。

    例如,如果你想了解上述逻辑,在记事本中打开一个 jpeg/png 图像,观察文件中的前 10-12 个字符,你可以在该文件中找到它们各自的文件扩展名

    所以我也在这里做同样的事情,我将在解码文件中搜索 GZIP 字符串,如果找到则该文件是 GZIP 格式,否则不是。这可能有点令人困惑。让我向您展示此代码: `

    var encodedData; //This one was fetched from the server
    var decodedData = atob(encodedData); //atob() decodes the string which is in base64 format
    var extension = "GZIP"
    var IndexOfGZIP = decodedData.IndexOf(extension) //Checking for GZIP word in decoded data
    
    //If it is equal to -1 it says that GZIP is not found in data
    if( IndexOfGZIP !== -1 ){ 
    
        //Normally the file extensions are found in the starting of the file only and hence I'm taking only first 11 characters into consideration.
        if( IndexOfGZIP >= 0 && IndexOfGZIP <=10 ){
            console.log("This is a GZIP file only")
        }else{
            console.log("File is not in GZIP Format")
        }
    }else{
        console.log("File is not in GZIP Format")
    }
    

    ` 希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 2016-12-14
      • 2011-07-28
      相关资源
      最近更新 更多