“This is the first day of my participation in the First Challenge 2022. For details: First Challenge 2022
Js + vue3 + TS + Element + vite. The database is cloud.mongodb. The project is still in the process of continuous development, we also welcome everyone star, if you have ideas, you can communicate with each other.
Today, take one of the pictures uploaded to do a share, the image uploaded using the hexadecimal system to determine the type of pictures some students will be confused, when uploading pictures, in fact, we can get the image suffix, that is,.jpg,.png and so on file format, why bother to use the hexadecimal system to judge? The suffix of the file name can be manually modified. After modification, it may not be accurate. This hexadecimal system is used for more accurate verification.
Vscode plug-in
If we’re going to use hexadecimal, how do we look at the encoding of the image? Vscode provides a great plugin hexdump for VScode. Right-click on the image and select Show hexdump to see the different file encodings
FileReader
We implement a transcoding through FileReader
FileReader MDN returns a newly constructed FileReader.
The FileReader object allows a Web application to asynchronously read the contents of a File (or raw data buffer) stored on the user’s computer, using a File or Blob object to specify which File or data to read.
reader.result
Is a character pass, convert it to an array- Converted to ASCII
- Convert to a hexadecimal string
- String padding padStart fills the specified padding string at the beginning of the original string until the new string is formed of the target length.
const blobToString = (blob) => { return new Promise((resolve) => { const reader = new FileReader() reader.onload = Function () {const res = read.result.split ('').map((v) => v.charcodeat ()) // transcode.map ((v) => V.tostring (16).toupperCase ()) // Convert to hexadecimal. Map ((v) => v.padstart (2, '0')) / / string fill. Join (") resolve (res)} reader. ReadAsBinaryString (blob)})}Copy the code
ReadAsBinaryString: Starts reading the contents of the specified Blob. Once this is done, the Result property holds the ArrayBuffer data object of the file being read.
Determine whether or not.gif
Take the first six digits in hexadecimal
const res = await blobToString(file.slice(0, 6))
const isGif = res == '47 49 46 38 39 61' || res == '47 49 46 38 37 61'
Copy the code
Determine whether or not.png
Take the first eight bits in hexadecimal
const res = await blobToString(file.slice(0, 8))
const isPng = res == '89 50 4E 47 0D 0A 1A 0A'
Copy the code
Determine whether or not.jpg
I’m going to take 2 bits at the beginning and 2 bits at the end
const start = await blobToString(file.slice(0, 2))
const tail = await blobToString(file.slice(-2, len))
const isJpg = start == 'FF D8' && tail == 'FF D9'
Copy the code