Home Web Front-end JS Tutorial javascript Convert from image to base64-bit encoded String_javascript trick

javascript Convert from image to base64-bit encoded String_javascript trick

May 16, 2016 pm 04:40 PM
base64 image coding

Recently, it is necessary to open the WeChat sharing method of the app to webview. When it comes to shared pictures, if the connection is through sending pictures, the picture files will be fetched again in the background, which will affect the speed. I choose webview to encode the image in base64. method to pass it to the local application. The following is the reference code for implementation:

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
<title>Image to Base64 - jsFiddle demo by handtrix</title> 

<script type='text/javascript' src='//code.jquery.com/jquery-2.0.2.js'></script> 

<link rel="stylesheet" type="text/css" href="/css/result-light.css" rel="external nofollow" > 

<style type='text/css'> 
@import url('//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css'); 

body{ 
padding: 20px; 
} 
</style> 

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){ 
/** 
* convertImgToBase64 
* @param {String} url 
* @param {Function} callback 
* @param {String} [outputFormat='image/png'] 
* @author HaNdTriX 
* @example 
convertImgToBase64('http://goo.gl/AOxHAL', function(base64Img){ 
console.log('IMAGE:',base64Img); 
}) 
*/ 
function convertImgToBase64(url, callback, outputFormat){ 
var canvas = document.createElement('CANVAS'); 
var ctx = canvas.getContext('2d'); 
var img = new Image; 
img.crossOrigin = 'Anonymous'; 
img.onload = function(){ 
canvas.height = img.height; 
canvas.width = img.width; 
ctx.drawImage(img,0,0); 
var dataURL = canvas.toDataURL(outputFormat || 'image/png'); 
callback.call(this, dataURL); 
// Clean up 
canvas = null; 
}; 
img.src = url; 
} 

$('#img2b64').submit(function(event){ 
var imageUrl = $(this).find('input[name=url]').val(); 
console.log('imageUrl', imageUrl); 
convertImgToBase64(imageUrl, function(base64Img){ 
$('.output') 
.find('textarea') 
.val(base64Img) 
.end() 
.find('a') 
.attr('href', base64Img) 
.text(base64Img) 
.end() 
.find('img') 
.attr('src', base64Img); 
}); 

event.preventDefault(); 
}); 

});//]]> 

</script> 
</head> 
<body> 
<h2>Input</h2> 
<form class="input-group" id="img2b64"> 
<input 
type="url" 
name="url" 
class="form-control" 
placeholder="Insert an IMAGE-URL" 
value="http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png" 
required> 
<span class="input-group-btn"> 
<input 
type="submit" 
class="btn btn-default"> 
</span> 
</form> 
<hr> 
<h2>Output</h2> 
<div class="output"> 
<textarea class="form-control"></textarea><br> 
<a></a><br><br> 
<img><br> 
</div> 
</body> 
</html>
Copy after login
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 common classification feature encoding techniques 11 common classification feature encoding techniques Apr 12, 2023 pm 12:16 PM

Machine learning algorithms only accept numerical input, so if we encounter categorical features, we will encode the categorical features. This article summarizes 11 common categorical variable encoding methods. 1. ONE HOT ENCODING The most popular and commonly used encoding method is One Hot Enoding. A single variable with n observations and d distinct values ​​is converted into d binary variables with n observations, each binary variable is identified by a bit (0, 1). For example: the simplest implementation after coding is to use pandas' get_dummiesnew_df=pd.get_dummies(columns=[‘Sex’], data=df)2,

How to safely disable Windows Modules Installer Worker on Windows 11 How to safely disable Windows Modules Installer Worker on Windows 11 Apr 13, 2023 pm 03:43 PM

Whether you have an old computer or need your PC to run many tasks simultaneously, you may want to disable the Windows Modules Installer worker. The reason is that the Windows Modules Installer worker places a high load on your disk, CPU, and memory. You may use the best software to fix high CPU usage, but some reports show that it can even take up 100% CPU usage. While it can help you maintain a more secure and reliable system, it comes at a cost. Therefore, you can decide to keep it or disable it to avoid performance issues. In this article, we will explore in detail what is Windows Modules Installer Worker and how to enable or

How many bytes do utf8 encoded Chinese characters occupy? How many bytes do utf8 encoded Chinese characters occupy? Feb 21, 2023 am 11:40 AM

UTF8 encoded Chinese characters occupy 3 bytes. In UTF-8 encoding, one Chinese character is equal to three bytes, and one Chinese punctuation mark occupies three bytes; while in Unicode encoding, one Chinese character (including traditional Chinese) is equal to two bytes. UTF-8 uses 1~4 bytes to encode each character. One US-ASCIl character only needs 1 byte to encode. Latin, Greek, Cyrillic, Armenian, and Hebrew with diacritical marks. , Arabic, Syriac and other letters require 2-byte encoding.

Knowledge graph: the ideal partner for large models Knowledge graph: the ideal partner for large models Jan 29, 2024 am 09:21 AM

Large language models (LLMs) have the ability to generate smooth and coherent text, bringing new prospects to areas such as artificial intelligence conversation and creative writing. However, LLM also has some key limitations. First, their knowledge is limited to patterns recognized from training data, lacking a true understanding of the world. Second, reasoning skills are limited and cannot make logical inferences or fuse facts from multiple data sources. When faced with more complex and open-ended questions, LLM's answers may become absurd or contradictory, known as "illusions." Therefore, although LLM is very useful in some aspects, it still has certain limitations when dealing with complex problems and real-world situations. In order to bridge these gaps, retrieval-augmented generation (RAG) systems have emerged in recent years. The core idea is

Several common encoding methods Several common encoding methods Oct 24, 2023 am 10:09 AM

Common encoding methods include ASCII encoding, Unicode encoding, UTF-8 encoding, UTF-16 encoding, GBK encoding, etc. Detailed introduction: 1. ASCII encoding is the earliest character encoding standard, using 7-bit binary numbers to represent 128 characters, including English letters, numbers, punctuation marks, control characters, etc.; 2. Unicode encoding is a method used to represent all characters in the world The standard encoding method of characters, which assigns a unique digital code point to each character; 3. UTF-8 encoding, etc.

How to use Bing Image Creator for free How to use Bing Image Creator for free Feb 27, 2024 am 11:04 AM

This article will introduce seven ways to get high-quality output using the free BingImageCreator. BingImageCreator (now known as ImageCreator for Microsoft Designer) is one of the great online artificial intelligence art generators. It generates highly realistic visual effects based on user prompts. The more specific, clear, and creative your prompts are, the better the results will be. BingImageCreator has made significant progress in creating high-quality images. It now uses Dall-E3 training mode, showing a higher level of detail and realism. However, its ability to consistently produce HD results depends on several factors, including fast

How to delete images from Xiaomi phones How to delete images from Xiaomi phones Mar 02, 2024 pm 05:34 PM

How to delete images on Xiaomi mobile phones? You can delete images on Xiaomi mobile phones, but most users don’t know how to delete images. Next is the tutorial on how to delete images on Xiaomi mobile phones brought by the editor. Interested users can come and join us. Let's see! How to delete images on Xiaomi mobile phone 1. First open the [Album] function in Xiaomi mobile phone; 2. Then check the unnecessary pictures and click the [Delete] button in the lower right corner; 3. Then click [Album] at the top to enter the special area , select [Recycle Bin]; 4. Then directly click [Empty Recycle Bin] as shown in the figure below; 5. Finally, directly click [Permanent Delete] to complete.

PHP coding tips: How to generate a QR code with anti-counterfeiting verification function? PHP coding tips: How to generate a QR code with anti-counterfeiting verification function? Aug 17, 2023 pm 02:42 PM

PHP coding tips: How to generate a QR code with anti-counterfeiting verification function? With the development of e-commerce and the Internet, QR codes are increasingly used in various industries. In the process of using QR codes, in order to ensure product safety and prevent counterfeiting, it is very important to add anti-counterfeiting verification functions to the QR codes. This article will introduce how to use PHP to generate a QR code with anti-counterfeiting verification function, and attach corresponding code examples. Before starting, we need to prepare the following necessary tools and libraries: PHPQRCode: PHP

See all articles