Jak przekonwertować obraz na ciąg base64 za pomocą javascript

Muszę przekonwertować mój obraz na ciąg base64, aby móc wysłać mój obraz na serwer. Czy jest do tego jakiś plik js?.. ? Else jak to przekonwertować

Author: Coder_sLaY, 2011-05-27

9 answers

Możesz użyć do tego HTML5 <canvas>:

Utwórz płótno, załaduj do niego obraz, a następnie użyj toDataURL() aby uzyskać reprezentację base64 (w rzeczywistości jest to URL data:, ale zawiera zakodowany obraz base64).

 147
Author: ThiefMaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-27 09:36:11

Istnieje wiele podejść do wyboru:

1. Podejście: FileReader

Załaduj obraz jako blob poprzez XMLHttpRequest i użyj FileReader API, aby przekonwertować go na 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)
})

Ten przykład kodu może być również zaimplementowany przy użyciu WHATWG API fetch :

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

Te podejścia:

  • brak w przeglądarce wsparcie
  • mieć lepszą kompresję
  • działa również dla innych typów plików

Obsługa Przeglądarki:


2. Podejście: Canvas

Załaduj obraz do obiektu obrazu, pomaluj go na nie skażone płótno i przekonwertuj płótno z powrotem na 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)
  }
)

W detail

Obsługiwane formaty wejściowe:

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

Obsługiwane formaty wyjściowe:

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

Obsługa Przeglądarki:


3. Podejście: zdjęcia z lokalnego system plików

Jeśli chcesz przekonwertować obrazy z systemu plików users, musisz przyjąć inne podejście. Użyj API FileReader :

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)" />
 623
Author: HaNdTriX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-02 21:59:13

Ten fragment może przekonwertować ciąg znaków, obraz, a nawet plik wideo do danych ciągów base64. Spróbuj raz...

<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>
 65
Author: user2314737,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-17 20:12:00

Oto co zrobiłem

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

A oto jak go używasz

base64( $('input[type="file"]'), function(data){
  console.log(data.base64)
})
 17
Author: James Harrington,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-30 19:21:38

Zasadniczo, jeśli twój obraz jest

<img id='Img1' src='someurl'>

Następnie można przekonwertować go jak

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();
 10
Author: mecek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 13:01:31

Możesz użyć FileAPI , ale nie jest obsługiwany.

 4
Author: Artem Tikhomirov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-01 22:13:33

Z tego co wiem obrazek może być konwertowany do ciągu Base64 albo za pomocą FileReader() albo przechowując go w elemencie canvas, a następnie za pomocą toDataURL() aby uzyskać obrazek.Miałem problem z simmilarem.

Konwertuj obraz na płótno, które jest już załadowane

 4
Author: Ajeet Lakhani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:26

Wypróbuj ten kod

File upload chnage event ccall 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();
}

Przechowuje base64data w ukrytym pliku do użycia.

 4
Author: ravi polara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-21 05:58:46

Cóż, jeśli używasz dojo, daje nam to bezpośredni sposób na kodowanie lub dekodowanie do base64.

Spróbuj tego:

Aby zakodować tablicę bajtów za pomocą dojox.kodowanie.base64:

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

Aby odszyfrować łańcuch kodowany base64:

var bytes = dojox.encoding.base64.decode(str);
 0
Author: Vikash Pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-27 15:15:37