0

i have below png blob which i want to convert to jpg blob. How can i achieve that?

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgQAAAK2CAYAAAAxAIToAAAAAXNSR0IArs4c6QAAIABJREFUeF7s......
lewis machilika
  • 819
  • 2
  • 11
  • 25
  • Does this answer your question? [How to convert Blob to File in JavaScript](https://stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript) – Ngatia Frankline Jul 13 '22 at 00:06

1 Answers1

1

You will have to redraw your blob using html canvas then convert it back to jpg blob, as follows:

var img = await document.createElement("img");
img.src = 'your_base_64_blob_string_here'
img.onload = function (event) {
  // This line is dynamically creating a canvas element
  var canvas = document.createElement("canvas")
  var ctx = canvas.getContext("2d");
  //Resize your image here
  ctx.drawImage(img, 0, 0, 400, 350);
  // To blob
  var jpgBlob = await new Promise(resolve => canvas.toBlob(resolve,'image/jpg', 1)); // refer to canvas.toblob API
  // To file
  var jpgFile = await new File([jpgblob], imagefilename.jpg, {type:'image/jpg'}); // refer to File API
}

I have not tested the code, please inform if it works. Be aware of browser compatibility.

Your can also get more information on this these similar posts (Don't worry about the title follow the answers):

  1. How to convert Blob to File in JavaScript
  2. Convert blob to image file
Ngatia Frankline
  • 2,897
  • 2
  • 20
  • 19