Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

javascript - How to get the image extension from a remote image url that doesn't contain image extension in the url

I'm trying to use the Image API to get the image data/extension for image urls.

I can easily use regex to the file extension from names like {domain}.com/path-to-image.jpg, but what about for image urls like: http://placekitten.com/g/1000/1000

I am trying to get a dataUrl for the image data at that location. This is the particular part of code where this data is needed. You can see currently I am hard coding 'image/png'.

  _getDataUri(url, callback) {
    const props = this.props;
    const img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');

    img.onload = function onLoadedImage() {
      const {minHeight, minWidth} = props.opt;
      const [width, height] = [img.width, img.height];

      const canvas = document.createElement('canvas');
      canvas.width = this.width;
      canvas.height = this.height;

      const ctx = canvas.getContext('2d');
      ctx.drawImage(this, 0, 0);

      const dataUrl = canvas.toDataURL('image/png');
      callback({
        dataUrl,
        height,
        minHeight,
        minWidth,
        width
      });
    };

    img.onerror = function onImageError() {
      props.opt.onModalClose();
      props.opt.onChangeCardStatus('invalidImage');
    };

    img.src = url;
  }

* Update * Fetch api will NOT solve this problem because it will not produce a readable response if you disable cors.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use fetch(), Response.blob(), FileReader.prototype.readAsDataURL()

fetch("http://placekitten.com/g/1000/1000")
.then(response => response.blob())
.then(blob => {
  console.log(blob.type);
  let reader = new FileReader();
  reader.onload = () => {
    console.log(reader.result)
  }
  reader.readAsDataURL(blob) 
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...