如何使用javascript将图像转换为base64字符串

时间:2022-04-24 09:39:36

I need to convert my image to a base64 string so that i can send my image to a server. Is there any js file for this... ? Else how to convert it

我需要将图像转换为base64字符串,以便可以将图像发送到服务器。这里有js文件吗?吗?还有如何转换它

9 个解决方案

#1


140  

You can use the HTML5 <canvas> for it:

可以使用HTML5 :

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表示(实际上,它是一个数据:URL,但它包含base64编码的图像)。

#2


585  

There are multiple approaches you can choose from:

你可以选择多种方法:

1. Approach: FileReader

Load the image as blob via XMLHttpRequest and use the FileReader API to 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

Load the image into an Image-Object, paint it to a non tainted canvas and convert the canvas back to a dataURL.

将图像加载到一个图像对象中,将其绘制到非受污染的画布上,并将画布转换为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)
  }
)

in detail

详细

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

图像/png,图像/jpeg,图像/jpg,图像/gif,图像/bmp,图像/tiff,图像/x-icon,图像/svg+xml,图像/webp,图像/xxx

Supported output formats:

支持输出格式:

image/png, image/jpeg, image/webp(chrome)

图像/ png图像/ jpeg图像/ webp(铬)

Browser Support:

浏览器支持:

  • http://caniuse.com/#feat=canvas
  • = http://caniuse.com/壮举画布
  • IE10 (IE10 just works with same origin images)

    IE10 (IE10只适用于相同的原始图像)


3. Approach: Images from the local file system

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)" />

#3


64  

This snippet could convert your string,image and even video file to base64 string data. Try it once...

这段代码可以将字符串、图像甚至视频文件转换为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>

#4


15  

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)
})

#5


5  

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, 0, 0, c.width, c.height);
var base64String = c.toDataURL();

#6


4  

You could use FileAPI, but it's pretty much unsupported.

您可以使用FileAPI,但它几乎不受支持。

#7


3  

As far as i know image can be converted into base64 string either by FileReader() or storing it in canvas element and then use toDataURL() to get image.I had the simmilar kind of problem you can refer this.

据我所知,图像可以通过FileReader()或将其存储在canvas元素中,然后使用toDataURL()来获取图像。我有一个simmilar的问题你可以参考这个。

Convert an image to canvas that is already loaded

将图像转换为已加载的画布

#8


1  

Try This code

试试这个代码

File upload Chnage event ccall this function

文件上传Chnage事件调用这个函数

  $("#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 base64data in hidden filed to use.

将base64data存储在隐藏文件中以供使用。

#9


0  

Well, if you are using dojo, it gives us direct way to encode or decode into base64.

如果您正在使用dojo,它将为我们提供对base64进行编码或解码的直接方式。

Try this:

试试这个:

To encode an array of bytes using dojox.encoding.base64:

使用dojox.encoding.base64对字节数组进行编码:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

解码一个base64编码的字符串:

var bytes = dojox.encoding.base64.decode(str);

#1


140  

You can use the HTML5 <canvas> for it:

可以使用HTML5 :

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表示(实际上,它是一个数据:URL,但它包含base64编码的图像)。

#2


585  

There are multiple approaches you can choose from:

你可以选择多种方法:

1. Approach: FileReader

Load the image as blob via XMLHttpRequest and use the FileReader API to 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

Load the image into an Image-Object, paint it to a non tainted canvas and convert the canvas back to a dataURL.

将图像加载到一个图像对象中,将其绘制到非受污染的画布上,并将画布转换为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)
  }
)

in detail

详细

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

图像/png,图像/jpeg,图像/jpg,图像/gif,图像/bmp,图像/tiff,图像/x-icon,图像/svg+xml,图像/webp,图像/xxx

Supported output formats:

支持输出格式:

image/png, image/jpeg, image/webp(chrome)

图像/ png图像/ jpeg图像/ webp(铬)

Browser Support:

浏览器支持:

  • http://caniuse.com/#feat=canvas
  • = http://caniuse.com/壮举画布
  • IE10 (IE10 just works with same origin images)

    IE10 (IE10只适用于相同的原始图像)


3. Approach: Images from the local file system

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)" />

#3


64  

This snippet could convert your string,image and even video file to base64 string data. Try it once...

这段代码可以将字符串、图像甚至视频文件转换为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>

#4


15  

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)
})

#5


5  

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, 0, 0, c.width, c.height);
var base64String = c.toDataURL();

#6


4  

You could use FileAPI, but it's pretty much unsupported.

您可以使用FileAPI,但它几乎不受支持。

#7


3  

As far as i know image can be converted into base64 string either by FileReader() or storing it in canvas element and then use toDataURL() to get image.I had the simmilar kind of problem you can refer this.

据我所知,图像可以通过FileReader()或将其存储在canvas元素中,然后使用toDataURL()来获取图像。我有一个simmilar的问题你可以参考这个。

Convert an image to canvas that is already loaded

将图像转换为已加载的画布

#8


1  

Try This code

试试这个代码

File upload Chnage event ccall this function

文件上传Chnage事件调用这个函数

  $("#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 base64data in hidden filed to use.

将base64data存储在隐藏文件中以供使用。

#9


0  

Well, if you are using dojo, it gives us direct way to encode or decode into base64.

如果您正在使用dojo,它将为我们提供对base64进行编码或解码的直接方式。

Try this:

试试这个:

To encode an array of bytes using dojox.encoding.base64:

使用dojox.encoding.base64对字节数组进行编码:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

解码一个base64编码的字符串:

var bytes = dojox.encoding.base64.decode(str);