如何从URL中不包含图像扩展名的远程图像URL获取图像扩展名 [英] How to get the image extension from a remote image url that doesn't contain image extension in the url
问题描述
我正在尝试使用Image API来获取图片网址的图片数据/扩展名。
I'm trying to use the Image API to get the image data/extension for image urls.
我可以轻松地使用正则表达式从文件扩展名中获取{domain} .com / path-to-image.jpg,但图片网址如下: http: //placekitten.com/g/1000/1000
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
我正在尝试为该位置的图像数据获取dataUrl。
这是需要此数据的代码的特定部分。你现在可以看到我很难编码'image / png'。
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;
}
*更新*
获取api不会解决这个问题,因为如果禁用cors它不会产生可读的响应。
* Update * Fetch api will NOT solve this problem because it will not produce a readable response if you disable cors.
推荐答案
你可以使用 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)
})
这篇关于如何从URL中不包含图像扩展名的远程图像URL获取图像扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!