2

I'm working with croppie js and the lib returns a blob object.

But for my website I have two options, use the blob for the Microsoft's OCR (which works perfectly) to have the text in the part of the image or have the part itself and so I need to open the blob to get the URL to put it in the src's field of an image element

I found this on https://developer.mozilla.org/fr/docs/Web/API/Blob

function write_img(blob)
{
    var reader = new FileReader();
    reader.addEventListener("loadend", function() {
        // reader.result contient le contenu du
        // blob sous la forme d'un tableau typé
        });
    reader.readAsDataURL(blob);
    document.getElementById("result").innerHTML += "<img src=\"" + reader.result + "\" >";
}

But it returns null, Is anyone able to help?

3
  • thanks a lot it work ! I didn't know readAsDataUrl was asynchronous and I don't know a lot about call backbut thank ! :) Commented Nov 7, 2017 at 13:16
  • see answer below - see my comment regarding which event you really should be listening for :p Commented Nov 7, 2017 at 13:17
  • yes thank I'm working on it :) ! Commented Nov 7, 2017 at 13:25

2 Answers 2

1

Use the URL.createObjectURL if you want to display images... avoid base64 since it takes up more memory & time to encode/decode base64

Object url will load faster and is also synchronous

function write_img(blob) {
  var img = new Image()

  img.src = URL.createObjectURL(blob)
  img.onload = function() {
    document.getElementById('result').appendChild(img)
    // revoke the url when it's not needed anymore.
    URL.revokeObjectURL(this.src)
  }

  img.onerror = function() {
    // not an image.
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

but it return null, any help ?

It returns null because loadend event is not fired yet.

This line

  document.getElementById("result").innerHTML += "<img src=\"" + reader.result + "\" >";

needs to be inside the loadend event handler

function write_img(blob)
{
    var reader = new FileReader();
    reader.addEventListener("load", function() {
        document.getElementById("result").innerHTML += "<img src=\"" + reader.result + "\" >";
     });
    reader.readAsDataURL(blob);
}

1 Comment

preferably listen for load not loadend - as loadend is fired for both success and failure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.