0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

imgタグのsrc属性に指定している画像をbase64変換してPOST送信する

Posted at

以下の手順。

  • imgタグに画像を読み込んだ直後、canvasタグを生成
  • 画像をcanvasタグに書き込む。
  • canvasタグのtoDataURL関数を使用してBase64の文字列に変換する。
  • 変換した結果を送信する。
<html>
<body>
<img id="baseimg" src="./1010609154.jpg" crossorigin="annonymous"  />
<div id="b64img"></div>
<script>
const imageBase = document.getElementById("baseimg");
imageBase.onload = function() {
    var canvas = document.createElement("canvas");
    canvas.width = this.width;
    canvas.height = this.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(this, 0, 0);
    var dataURL = canvas.toDataURL("image/jpeg");
    // 変換後の文字列をブラウザを表示
    document.getElementById('b64img').innerHTML = dataURL;
    // 送信
    sendBase64(dataURL);
};

const server_url='送信先URL';

function sendBase64(base64) {
  fetch(server_url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      base64String: base64
    })
  }).then(response => {
     return  response.json();
  }).then(data => {
     console.log(data);
  }).catch(error => {
     // console.log(error);
  });
};
</script>
</body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?