简体   繁体   中英

Display image from ID3 image data using javascript

I've tried all of the methods I could find in stackoverflow. This two are some of the most complete posts:

Display image from blob using javascript and websockets

How can you encode a string to Base64 in JavaScript?

I'm using cloudinary and id3js. First I upload the mp3 file to cloudinary, then I request the file with Ajax through id3js. This gives me all of the ID3 tags.

  openUploadModal() {
      cloudinary.openUploadWidget(window.cloudinaryOptions,
      (errors, track) => {
          if(!values(errors).length) {

              id3(track[0].secure_url, (errs, tags) => {
                  this.setState({
                      title: tags.title,
                      audio_url: track[0].secure_url,
                      artist: tags.artist,
                      uploaded: true,
                      cover_photo: this.getImage(tags.v2.image)
                   });
               });
           }
      });
  }

And the image converter:

getImage(image) {
    var arrayBuffer = image.data;
    var bytes = new Uint8Array(arrayBuffer);

    return  "data:image/png;base64,"+btoa(unescape(encodeURIComponent(bytes)));
}

This is what the tags object looks like:

在此处输入图片说明

I then use the return value of getImage in the background-image attribute of a div. There are no errors in the console (not a bad request) but when opening the data:image/jpg;base64,... link there's only a little white square on the page.

How can I get a working url from the image object in the ID3 tags?

If image.data is an ArrayBuffer , you can use FileReader . FileReader load event is asynchronous, you cannot return the result from the function without using Promise , though you can use FileReaderSync() at Worker .

See also createImageBitmap alternative on Safari .

var reader = new FileReader();
reader.onload = function() {
  // do stuff with `data URI` of `image.data`
  console.log(reader.result);
}
reader.readAsDataURL(new Blob([image.data], {type:image.mime}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM