CONVERT图像URL到Base64

时间:2014-03-04 12:57:34

标签: javascript jquery

使用图像文件,我得到一个图像的网址,需要发送到网络服务。从那里,图像必须在我的系统上本地保存。

我正在使用的代码:

var imagepath = $("#imageid").val();// from this getting the path of the selected image

that var st = imagepath.replace(data:image/png or jpg; base64"/"");

如何将图片网址转换为BASE64?

11 个答案:

答案 0 :(得分:75)

<强> HTML

<img id=imageid src=https://www.google.de/images/srpr/logo11w.png>

<强>的JavaScript

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

var base64 = getBase64Image(document.getElementById("imageid"));

此方法需要canvas元素,即perfectly supported

答案 1 :(得分:27)

通过@HaNdTriX

查看此答案:https://stackoverflow.com/a/20285053/5065874

基本上,他实现了这个功能:

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(imagepath, function(myBase64) {
    console.log(myBase64); // myBase64 is the base64 string
});

答案 2 :(得分:2)

这是你的HTML -

    <img id="imageid" src="">
    <canvas id="imgCanvas" />

Javascript应该是 -

   var can = document.getElementById("imgCanvas");
   var img = document.getElementById("imageid");
   var ctx = can.getContext("2d");
   ctx.drawImage(img, 10, 10);
   var encodedBase = can.toDataURL();

'encodedBase'包含Image64的Base64编码。

答案 3 :(得分:1)

没关系,谢谢!

SELECT *
FROM   table_name t
WHERE  EXISTS (
  WITH input ( value ) AS (
    SELECT '123,789' FROM DUAL -- Your input value
  )
  SELECT 1
  FROM   input
  WHERE  ','||t.product_id||',' LIKE '%,' || REGEXP_SUBSTR( value, '[^,]+', 1, LEVEL ) || ',%'
  CONNECT BY LEVEL <= REGEXP_COUNT( value, '[^,]+' )
  HAVING COUNT(*) = REGEXP_COUNT( value, '[^,]+' )
)

答案 4 :(得分:0)

majority

答案 5 :(得分:0)

您可以使用:

function ViewImage(){
 function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}

添加到您的输入中onchange = ViewImage();

答案 6 :(得分:0)

这是Abubakar Ahmad的答案的打字稿版本

function imageTo64(
  url: string, 
  callback: (path64: string | ArrayBuffer) => void
): void {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();

  xhr.onload = (): void => {
    const reader = new FileReader();
    reader.readAsDataURL(xhr.response);
    reader.onloadend = (): void => callback(reader.result);
  }
}

答案 7 :(得分:-1)

let baseImage = new Image;
baseImage.setAttribute('crossOrigin', 'anonymous');
baseImage.src = your image url

var canvas = document.createElement("canvas");
  canvas.width = baseImage.width;
  canvas.height = baseImage.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(baseImage, 0, 0);
  var dataURL = canvas.toDataURL("image/png");

有关&#34;启用CORS的图像的附加信息&#34;:MDN Documentation

答案 8 :(得分:-1)

imageToBase64 = (URL) => {
    let image;
    image = new Image();
    image.crossOrigin = 'Anonymous';
    image.addEventListener('load', function() {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        canvas.width = image.width;
        canvas.height = image.height;
        context.drawImage(image, 0, 0);
        try {
            localStorage.setItem('saved-image-example', canvas.toDataURL('image/png'));
        } catch (err) {
            console.error(err)
        }
    });
    image.src = URL;
};

imageToBase64('image URL')

答案 9 :(得分:-1)

我尝试使用top answer,但发生在Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported

我发现这是由于cross domain problems造成的,解决方案是

function convert(oldImag, callback) {
    var img = new Image();
    img.onload = function(){
        callback(img)
    }
    img.setAttribute('crossorigin', 'anonymous');
    img.src = oldImag.src;
}
function getBase64Image(img,callback) {
    convert(img, function(newImg){
        var canvas = document.createElement("canvas");
        canvas.width = newImg.width;
        canvas.height = newImg.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(newImg, 0, 0);
        var base64=canvas.toDataURL("image/png");
        callback(base64)
    })
}
getBase64Image(document.getElementById("imageid"),function(base64){
    console.log(base64)
});

答案 10 :(得分:-1)

在当今的JavaScript中,它也可以正常工作。

const getBase64FromUrl = async (url) => {
  const data = await fetch(url);
  const blob = await data.blob();
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob); 
    reader.onloadend = function() {
      const base64data = reader.result;   
      resolve(base64data);
    }
  });
}

getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)