如何使用 JavaScript 将图像转换为 Base64 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6150289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert an image into Base64 string using JavaScript?
提问by Coder_sLaY
I need to convert my image to a Base64 string so that I can send my image to a server.
我需要将图像转换为 Base64 字符串,以便将图像发送到服务器。
Is there any JavaScript file for this? Else, how can I convert it?
是否有任何 JavaScript 文件?否则,我该如何转换它?
采纳答案by ThiefMaster
You can use the HTML5 <canvas>
for it:
您可以使用 HTML5 <canvas>
:
Create a canvas, load your image into it and then use toDataURL()
to get the Base64 representation (actually, it's a data:
URL, but it contains the Base64-encoded image).
创建一个画布,将图像加载到其中,然后使用它toDataURL()
来获取 Base64 表示(实际上,它是一个data:
URL,但它包含 Base64 编码的图像)。
回答by HaNdTriX
There are multiple approaches you can choose from:
您可以选择多种方法:
1. Approach: FileReader
1.方法:FileReader
Load the image as blob via XMLHttpRequestand use the FileReader APIto convert it to a dataURL:
通过XMLHttpRequest将图像加载为 blob并使用FileReader API将其转换为dataURL:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
This code example could also be implemented using the WHATWG fetch API:
这个代码示例也可以使用 WHATWG fetch API来实现:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')
.then(dataUrl => {
console.log('RESULT:', dataUrl)
})
These approaches:
这些方法:
- lack in browser support
- have better compression
- work for other file types as well
- 缺乏浏览器支持
- 有更好的压缩
- 也适用于其他文件类型
Browser Support:
浏览器支持:
2. Approach: Canvas
2.方法:画布
Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.
将图像加载到 Image-Object 中,将其绘制到未受污染的画布上并将画布转换回 dataURL。
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)
Supported input formats:
支持的输入格式:
image/png
, image/jpeg
, image/jpg
, image/gif
, image/bmp
, image/tiff
, image/x-icon
, image/svg+xml
, image/webp
, image/xxx
image/png
, image/jpeg
, image/jpg
, image/gif
, image/bmp
, image/tiff
, image/x-icon
, image/svg+xml
, image/webp
,image/xxx
Supported output formats:
支持的输出格式:
image/png
, image/jpeg
, image/webp
(chrome)
image/png
, image/jpeg
, image/webp
(铬)
Browser Support:
浏览器支持:
- http://caniuse.com/#feat=canvas
Internet Explorer 10 (Internet Explorer 10 just works with same origin images)
- http://caniuse.com/#feat=canvas
Internet Explorer 10(Internet Explorer 10 仅适用于同源图像)
3. Approach: Images from the local file system
3.方法:来自本地文件系统的图像
If you want to convert images from the users file system you need to take a different approach. Use the FileReader API:
如果要从用户文件系统转换图像,则需要采用不同的方法。使用FileReader API:
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
回答by ThiefMaster
This snippet can convert your string, image and even video file to Base64 string data.
此代码段可以将您的字符串、图像甚至视频文件转换为 Base64 字符串数据。
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
回答by mehmet mecek
Basically, if your image is
基本上,如果您的图像是
<img id='Img1' src='someurl'>
then you can convert it like
然后你可以像这样转换它
var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();
回答by James Harrington
Here is what I did:
这是我所做的:
// Author James Harrington 2014
function base64(file, callback){
var coolFile = {};
function readerOnload(e){
var base64 = btoa(e.target.result);
coolFile.base64 = base64;
callback(coolFile)
};
var reader = new FileReader();
reader.onload = readerOnload;
var file = file[0].files[0];
coolFile.filetype = file.type;
coolFile.size = file.size;
coolFile.filename = file.name;
reader.readAsBinaryString(file);
}
And here is how you use it
这是你如何使用它
base64( $('input[type="file"]'), function(data){
console.log(data.base64)
})
回答by jonathana
I found that the most safe and reliable way to do it is to use FileReader()
.
我发现最安全可靠的方法是使用FileReader()
.
Demo: Image to Base64
演示:图像转 Base64
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="myinput" type="file" onchange="encode();" />
<div id="dummy">
</div>
<div>
<textarea style="width:100%;height:500px;" id="txt">
</textarea>
</div>
<script>
function encode() {
var selectedfile = document.getElementById("myinput").files;
if (selectedfile.length > 0) {
var imageFile = selectedfile[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result;
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("dummy").innerHTML = newImage.outerHTML;
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
回答by Shubham
If you have a file object, this simple function will work:
如果你有一个文件对象,这个简单的函数将起作用:
function getBase64 (file, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(file);
}
Usage example:
用法示例:
getBase64(fileObjectFromInput, function(base64Data){
console.log("Base64 of file is", base64Data); // Here you can have your code which uses Base64 for its operation, // file to Base64 by oneshubh
});
回答by ravi polara
Try this code:
试试这个代码:
For a file upload change event, call this function:
对于文件上传更改事件,调用此函数:
$("#fileproof").on('change', function () {
readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr = new FileReader();
fr.onload = function (e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL(files[0]);
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
Store Base64 data in hidden filed to use.
将 Base64 数据存储在隐藏文件中以供使用。
回答by Ajeet Lakhani
As far as I know, an image can be converted into a Base64 string either by FileReader() or storing it in the canvas element and then use toDataURL() to get the image. I had the similar kind of problem you can refer this.
据我所知,图像可以通过 FileReader() 转换为 Base64 字符串,也可以将其存储在 canvas 元素中,然后使用 toDataURL() 获取图像。我有类似的问题,你可以参考这个。