Home  >  Article  >  Web Front-end  >  Examples of conversion between base64 strings and images

Examples of conversion between base64 strings and images

小云云
小云云Original
2018-03-17 14:54:263385browse

1. The principle of converting a base64 string to an image is that when the base64 string is used as the src attribute of the img tag, if it is valid, it can be previewed. If you want to download, create a new a tag, set the href attribute of the a tag to the base64 string, set the download attribute of the a tag to the file name, and then manually trigger the click event of the a tag through js, then the download behavior is completed. (Depending on the browser, you may need to select the download directory or use the default directory).

2. Convert images to base64 strings

There are two types, one is to provide the src tag of the image, and the other is to upload the image file.

3. Provide the src tag of the image

This needs to be done with the help of the canvas tag.
The advantage is...can you zoom in on the picture?

The disadvantage is that it cannot cross domains (but neither does the other one)

The sequence is as follows:
1. The user provides src
2. Create a new img tag and set the src Give the img tag
3. After the img tag is loaded (the onload callback is triggered), continue to execute the following code:
4. Write the image to canvas (at this time, you can set the size of the canvas according to the image size, or let the image Adaptive canvas size)
5. Get the base64 string through the toDataURL method of canvas
6. Output the base64 string;

4. File upload form
Requires input tag support type =file, you need to use the FileReader object
The advantage is that it automatically converts the file after selecting it, making the operation simpler.
The sequence is as follows:
1. When the input tag of type=file triggers the onchange event, start executing the following instructions
2. Create a new FileReader object;
3. Use its readAsDataURL API , read the file content;
4. When the reading is successful (the onload callback function is triggered), you can use the parameter e of the callback function to obtain the base64 string using the attribute e.target.result;
5. The base64 The string is what is needed.

5.DEMO page:

Convert image to base64 string
Convert base64 string to image

Related recommendations:

PHP code to convert images into base64 string

The above is the detailed content of Examples of conversion between base64 strings and images. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn