Andreas Selenwall
Andreas Selenwall

Reputation: 5795

Can't create Base64 representation of binary JPEG

So, this must be something more than I have to struggle with. I let users store images, now privately, hence I need to be able to request images with the Authorization header. <img> doesn't allow this however (and no, I don't want to add a ?token=xxx to the request). So I have to load the image using axios.get and then convert the binary representation of the image to Base64, and embed the image using the Data URI. Simple, right?

So what I have to do is img.src=data:image/jpeg;base64,xxxxxxxxx where all the x:s should be replaced with the Base64 representation of the image. I tried using btoa but only got about 20 characters in my Base64. The image is on 700Kb.

I do not use browserify or webpack, so I don't want to use Buffer to solve this.

EDIT: The first comment I received was actually the correct answer to my question, with just a small adjustment.

  getBase64(arrayBuffer) {
    var reader = new FileReader();
    var that = this;
    reader.onloadend = function () {
      that.mainImage = reader.result;
    };

    reader.readAsDataURL(new Blob([new Uint8Array(arrayBuffer)], { type: 'image/jpeg' }));
  }

I added a Blob to contain my ArrayBuffer, and I had to convert ArrayBuffer to UInt8Array for the blob to be able to iterate over it.

And in my Vue template

<img class="responsive-img" :src="mainImage"></img>

Upvotes: 1

Views: 49

Answers (1)

Pratik Patel
Pratik Patel

Reputation: 6978

try this.

getBase64(file) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
          console.log(reader.result);
        };
      },

this.getBase64(this.selected_file);

Upvotes: 1

Related Questions