我需要将我的图像转换为Base64字符串,这样我就可以将我的图像发送到服务器。
有JavaScript文件吗?否则,我如何转换它?
我需要将我的图像转换为Base64字符串,这样我就可以将我的图像发送到服务器。
有JavaScript文件吗?否则,我如何转换它?
你可以使用HTML5 <canvas>:
创建一个画布,将图像加载到其中,然后使用toDataURL()来获得Base64表示(实际上,它是一个data: URL,但它包含Base64编码的图像)。
如果您使用的是Dojo Toolkit,那么它为我们提供了一种直接编码或解码Base64的方法。
试试这个:
使用dojox.encoding.base64对字节数组进行编码:
var str = dojox.encoding.base64.encode(myByteArray);
解码一个base64编码的字符串:
var bytes = dojox.encoding.base64.decode(str);
有多种方法可供选择:
1. 方法:FileReader
通过XMLHttpRequest加载图像为blob,并使用FileReader API (readAsDataURL())将其转换为dataURL:
函数toDataURL(url,回调){ var xhr = new XMLHttpRequest(); xhr。Onload = function() { var reader = new FileReader(); 读者。Onloadend = function() { 回调(reader.result); } reader.readAsDataURL (xhr.response); }; xhr。打开(‘得到’,url); xhr。responseType = 'blob'; xhr.send (); } toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',函数(dataUrl) { dataUrl console.log('结果:') })
这个代码示例也可以使用WHATWG获取API来实现:
const toDataURL => .then(response => response.blob()) .then(blob => new Promise((resolve, reject) => { const reader = new FileReader() 读者。Onloadend = () => resolve(reader.result) 读者。Onerror =拒绝 reader.readAsDataURL (blob) })) toDataURL(“https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0”) .then(dataUrl => { dataUrl console.log('结果:') })
这些方法:
有更好的压缩 也适用于其他文件类型
浏览器支持:
http://caniuse.com/#feat=filereader http://caniuse.com/#feat=fetch
2. 方法:Canvas(适用于旧浏览器)
将图像加载到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) } )
详细
支持的输入格式:
图像/PNG, 图像/JPEG, 图像/JPG, 图像/gif, 图像/BMP, 图像/tiff, 图像/x-icon, 图像/SVG+XML, 图像/WebP, 图像/XXX
支持的输出格式:
图像/PNG, 图像/JPEG, 图像/WebP(Chrome)
浏览器支持:
http://caniuse.com/#feat=canvas Internet Explorer 10 (Internet Explorer 10只能处理相同来源的图像)
3.方法:来自本地文件系统的映像
如果您想从用户文件系统转换映像,则需要采用不同的方法。 使用FileReader API:
函数encodeImageFileAsURL(element) { Var file = element.files[0]; var reader = new FileReader(); 读者。Onloadend = function() { console.log(“结果”,reader.result) } reader.readAsDataURL(文件); } <input type="file" onchange="encodeImageFileAsURL(this)"/>
这个代码片段可以将你的字符串、图像甚至视频文件转换为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>
据我所知,图像可以通过FileReader()转换为Base64字符串,也可以将其存储在canvas元素中,然后使用toDataURL()获取图像。我也遇到过类似的问题你可以参考这个。
将图像转换为已经加载的画布
以下是我所做的:
// 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);
}
下面是你如何使用它
base64( $('input[type="file"]'), function(data){
console.log(data.base64)
})
基本上,如果你的形象是
<img id='Img1' src='someurl'>
然后你可以把它转换成
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();
试试下面的代码:
对于文件上传更改事件,调用这个函数:
$("#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();
}
存储Base64数据在隐藏的字段使用。
如果你有一个文件对象,这个简单的函数将工作:
function getBase64 (file, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(file);
}
使用的例子:
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
});
我发现最安全可靠的方法是使用FileReader()。
演示:映像到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>
更新-相同的代码与评论@AnniekJ请求:
<!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() {
// Get the file objects that was selected by the user from myinput - a file picker control
var selectedfile = document.getElementById("myinput").files;
// Check that the user actually selected file/s from the "file picker" control
// Note - selectedfile is an array, hence we check it`s length, when length of the array
// is bigger than 0 than it means the array containes file objects
if (selectedfile.length > 0) {
// Set the first file object inside the array to this variable
// Note: if multiple files are selected we can itterate on all of the selectedfile array using a for loop - BUT in order to not make this example complicated we only take the first file object that was selected
var imageFile = selectedfile[0];
// Set a filereader object to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
var fileReader = new FileReader();
// We declare an event of the fileReader class (onload event) and we register an anonimous function that will be executed when the event is raised. it is "trick" we preapare in order for the onload event to be raised after the last line of this code will be executed (fileReader.readAsDataURL(imageFile);) - please read about events in javascript if you are not familiar with "Events"
fileReader.onload = function(fileLoadedEvent) {
// AT THIS STAGE THE EVENT WAS RAISED
// Here we are getting the file contents - basiccaly the base64 mapping
var srcData = fileLoadedEvent.target.result;
// We create an image html element dinamically in order to display the image
var newImage = document.createElement('img');
// We set the source of the image we created
newImage.src = srcData;
// ANOTHER TRICK TO EXTRACT THE BASE64 STRING
// We set the outer html of the new image to the div element
document.getElementById("dummy").innerHTML = newImage.outerHTML;
// Then we take the inner html of the div and we have the base64 string
document.getElementById("txt").value = document.getElementById("dummy").innerHTML;
}
// This line will raise the fileReader.onload event - note we are passing the file object here as an argument to the function of the event
fileReader.readAsDataURL(imageFile);
}
}
</script>
</body>
</html>
uploadProfile(e) {
let file = e.target.files[0];
let reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
下面是使用Javascript Promise的方法。
const getBase64 = (file) => new Promise(function (resolve, reject) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject('Error: ', error);
})
现在,在事件处理程序中使用它。
const _changeImg = (e) => {
const file = e.target.files[0];
let encoded;
getBase64(file)
.then((result) => {
encoded = result;
})
.catch(e => console.log(e))
}
document.querySelector(“输入”)。Onchange = e => { const fr = new FileReader() Fr.onloadend = () => document.write(fr.result) fr.readAsDataURL (e.target.files [0]) } < input type = " file " >
需要利用读取器将blob转换为base64,更喜欢使用async-await语法,所以我选择提取读取器逻辑到帮助器,像这样:
//* Convert resBlob to base64
export const blobToData = (blob: Blob) => {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.readAsDataURL(blob)
})
}
并在主代码中使用await调用它:
//* Convert resBlob to dataUrl and resolve
const resData = await blobToData(resBlob)
我最终使用了一个返回Promise的函数。
const getImg64 = async() => { const convertImgToBase64URL = (url) => { console.log(url) return new Promise((resolve, reject) => { const img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = () => { let canvas = document.createElement('CANVAS') const ctx = canvas.getContext('2d') canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); const dataURL = canvas.toDataURL(); canvas = null; resolve(dataURL) } img.src = url; }) } //for the demonstration purposes I used proxy server to avoid cross origin error const proxyUrl = 'https://cors-anywhere.herokuapp.com/' const image = await convertImgToBase64URL(proxyUrl+'https://image.shutterstock.com/image-vector/vector-line-icon-hello-wave-260nw-1521867944.jpg') console.log(image) } getImg64()
你可以在任何异步函数中使用这种方法。然后,您只需等待转换后的图像并继续执行指示即可。
如果您遇到cors源错误,有一个简单的代理,称为cors-fix,它在服务器上加载图像并将其作为缓冲区数组返回。
因此,我们可以使用fetch来获取图像数据,并使用filereader将其转换为dataUrl,如@HaNdTriX所述。
function toDataUrl(url) {
fetch(`https://cors-fix.web.app/v1?url=${url}`)
.then(data => data.blob().then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
console.log(reader.result);
};
reader.onerror = () => {
console.log('reader error');
};
reader.readAsDataURL(blob);
}));
}
你也可以简单地提取以64为基数的URL的一部分:
var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part
假设您在浏览器中执行此操作:
等待:
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' });
return window.URL.createObjectURL(response.data);
与承诺
import axios from 'axios'
const response = await axios.get(url, { responseType: 'blob' })
.then((response) => {
const dataUrl = window.URL.createObjectURL(response.data);
// do something with your url
});
这很简单。 只需调用函数并传递你的图像。 2>保存返回值并在任何需要的地方使用。
//call like this
const convertedFile = await imageToBase64(fileObj);
console.log("convertedFile",convertedFile);
//this is the required function
async function imageToBase64(image) {
const reader = new FileReader();
reader.readAsDataURL(image);
const data= await new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
return data;
}
export default imageToBase64;