0

I have a Javascript code that creates a base64 image, but now I want to extract the image data from that base64 image. How do I do it? You can see the script live here.

Javascript:

function createBadge(img) {
  var c = document.createElement("canvas");
  var ctx = c.getContext("2d");
  c.width = img.width;
  c.height = img.height;
  var title = "Your preferences:";
  var prefer = preferences.reduce(function(acc, pref, ind) {
    return acc.concat([(ind + 1) + ': ' + pref])
  }, []);
  var text1 = "Don't forget to send your 1-page registration form by e-mail or post to your",
    text2 = "Commune or drop it off in person before the 31st of July!",
    text3 = "More info at www.vote.brussels";
  ctx.drawImage(img, 0, 0);
  // Filtro
  ctx.fillStyle = "#000000";
  ctx.globalAlpha = 0.51;
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.globalAlpha = 1;
  // Titolo
  ctx.fillStyle = "#fb4164";
  ctx.font = "500 69px Montserrat";
  ctx.fillText(title, 10, 65);
  // Preferenze
  ctx.fillStyle = "#ffffff";
  ctx.font = "28px Montserrat";
  var int = 60;
  var y = 130;
  prefer.forEach(function(str) {
    ctx.fillText(str, 50, y);
    y += int;
  });
  // Testo
  ctx.fillStyle = "#ffffff";
  ctx.font = "28px Montserrat";
  ctx.textAlign = "center";
  ctx.fillText(text1, c.width / 2, c.height - 130);
  ctx.fillText(text2, c.width / 2, c.height - 90);
  ctx.fillText(text3, c.width / 2, c.height - 20);
  img.src = c.toDataURL();
}

HTML:

<img id="basebadge" src="https://www.lucapolidori.eu/VoteBrussels/wp-content/uploads/2018/06/share-1.png" class="centered">

P.S. I need the data so I can decode the image and save it to the server as a PNG image.

D L
  • 25
  • 1
  • 8
  • can't that function just do a `return c.toDataURL()` at the end so you can use the return value to do whatever you need to it (e.g. send it to the server via AJAX) ? – apokryfos Jul 16 '18 at 10:16
  • Possible duplicate of [How to save an HTML5 Canvas as an image on a server?](https://stackoverflow.com/questions/13198131/how-to-save-an-html5-canvas-as-an-image-on-a-server) – Ahmed Yousif Jul 16 '18 at 11:32

0 Answers0