primers

Request an image, the data type returned is binary, to display the image.

  • Origin
  • My GitHub

Image SRC for binary processing

In this scenario, I first think of the situation where the SRC of the picture is base64. After I understand base64, I think it is theoretically feasible. Similar doubts and problems were found by querying the information. The solutions provided in the reply were as follows:

  1. useURL.createObjectURL()Methods.
  2. usewindow.btoa()Methods.
  3. useFileReaderThe object’sreadAsDataURL()Methods.

Let’s do the validation separately.

methods

URL.createObjectURL()

The URL object is used to parse, construct, normalize, and encode URLs (Uniform Resource Locators). It has two static methods:

  • URL.createObjectURL(): create aDOMString, which contains oneURLtheURLRepresents the parameter object passed to this method. thisURLLifecycle and the window in which it was createddocumentBinding. This newURLObject represents the specifiedFileObject orBlobObject.
  • URL.revokeObjectURL(): Release one before via the callURL.createObjectURL()Created that already existsURLObject. Browsers will automatically release documents when they exit, but for best performance and memory usage, when they are finished using oneURLObject, you should call this method to let the browser know that it no longer needs to keep a reference to the file.

This is a test example. Scan the QR code to access it as follows.

Results: The method is feasible. For compatibility see Can I Use CreateObjectURL? .

window.btoa()

The window.btoa() method creates a base-64-encoded ASCII String from the String, where each character in the String is treated as a binary data byte.

The corresponding method is window.atob(), which decodes the base-64 encoded string.

This is a test example. Scan the QR code to access it as follows.

Results: InvalidCharacterError was found and the method was not feasible. Even if you code it first, as the documentation says, it doesn’t work. If you think about it, what this method does is it creates a new string, not restores all types of original data.

One scenario where this method is used is to encode, transmit data that might cause communication problems, and then decode the data again using the atob() method.

For compatibility see Can I use BTOA? .

readAsDataURL()

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 the File or data to read. Its own method, readAsDataURL(), begins reading the contents of the specified BLOB. Once completed, the result property will contain a string in data: URL format to represent the contents of the read file.

This is a test example. Scan the QR code to access it as follows.

Results: The method is feasible. For compatibility see Can I use FileReader? .

The resources

  • Blob
  • File
  • URL
  • btoa
  • FileReader