I am working on a web app, the flow is something like that: the browser getting images from a server as a base64 data, then JavaScript encoding those images etc. (as a web server we are using apache with mod_deflate' module) I want to check are those getting images compressed (gzipped) or not.
Well, the problem is that there are no HTTP headers for the base64 images, so how can I check that? any idea? thanks.
If you are requesting the image data from a server the response will always have some headers and if the contents are compressed (gzipped) you will see the header content-encoding: gzip
.
However, if you want to know if the actual (base64 encoded) data is compressed (gzipped) you would decode the first 4 characters of the base64 string to get at least the first 2 bytes. If the first two bytes are 1F 8B
you are dealing with gzipped data.
If the first 2 bytes are 50 4B
it's zipped data. If the first 3 bytes are FF D8 FF
it's jpg/jpeg data. If the first 4 bytes are 89 50 4E 47
it's png data.
You are fetching the image from the server in base64 format so now decode the image which is in base64 format and store the output in a variable. Now lets see the decoded string and check the starting 10-12 characters of the decoded string because file extensions are stored in the starting of the file.
For example, if you want to understand the above logic open an jpeg/png image in notepad and observe the first 10-12 character in the file and you can find their respective file extensions in that file .
So I'm also doing the same thing here I will search for GZIP string in the decoded file, if its found then the file is in GZIP Format else its not.It may be a bit confusing. Let me show you the code for this : `
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")
}
` Hope this helps you.
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.