Search code examples
html5-canvas

Convert png blob to jpg blob in javascript


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

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgQAAAK2CAYAAAAxAIToAAAAAXNSR0IArs4c6QAAIABJREFUeF7s......

Solution

  • 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