JS image to Base64
Sometimes you need to insert a picture into the HTML, you can not find a suitable network after the online to store these pictures, there is no way to convert the picture into text, and then directly into the HTML, through the Base64 encoding can solve the problem.
Nonsense not much to say directly on the code, do not know what is Base64 's own Baidu.
Code
- <! DOCTYPE html>
- <meta CharSet="UTF-8">
- <title> JS image to Base64</title>
- <script src="//cdn.bootcss.com/jquery/2.2.0/jquery.min.js"></script>
- <script>
- function Run (input_file,get_data) {
- /*input_file: File button Object */
- /*get_data: How to execute after successful conversion */
- if ( typeof(filereader) = = = ' undefined ' ) {
- Alert ("Sorry, your browser does not support FileReader and cannot convert the picture to Base64, please use modern browser operation!") ");
- } else {
- Try {
- / * image to Base64 core code * /
- var file = input_file. Files[0];
- //Here we judge the type if it is not a picture to return to remove can upload arbitrary files
- if (! /image\/\w+/ . Test (file. Type)) {
- Alert ("Make sure the file is an image type");
- return False ;
- }
- var reader = new filereader();
- Reader. onload = function (){
- Get_data (this. ) Result);
- }
- Reader. Readasdataurl (file);
- }catch (e) {
- Alert (' picture turns Base64 wrong! '+ e. toString ())
- }
- }
- }
- $ (function () {
- $ ("input"). Change (function () {
- Run (this, function (data) {
- $ (' img '). attr (' src ',data);
- $ (' textarea '). Val (data);
- });
- });
- });
- </script>
- <body>
- <input type="file">
- style="max-height:300px;" >
- <textarea style="Display:block; width:100%;height:30em; " ></textarea>
- </body>
use of Base64 pictures
-
BASE64 format
-
DATA:[][;CHARSET=][;BASE64],
-
The use of Base64 in CSS
-
. demoimg{Background-image:url ("Data:image/jpg;base64,/9j/4qmzrxhpzgaasukqaagaaaal ....");
-
The use of Base64 in HTML
-
JS image to Base64