您可能无法始终获得高分辨率图像。此外,对于某些图书搜索结果,您可能根本无法获得任何图像。
我正在做一个类似的项目,我不得不手动检查我在回复中得到的每张图片的分辨率,我只选择了“好”的图片。这是我必须做的:
let newArr = [];
let lowResImage = 0;
let dataWithoutImage = 0;
let highResImage = 0;
genreResults?.forEach((book, index) => {
if (book?.volumeInfo?.imageLinks?.smallThumbnail) {//the current book has an image
mypromise(book.volumeInfo.imageLinks.smallThumbnail).then((res) => {
++highResImage;
newArr.push(book)
}).catch(error => {
++lowResImage;
}).finally(() => {
if (dataWithoutImage + highResImage + lowResImage === genreResults.length) {
console.log("---------data populated----------");
console.log("highResolutionImages", highResImage);
console.log("low resolution images:", lowResImage);
console.log("booksWithoutImages", dataWithoutImage);
console.log("genreResults size", genreResults.length)
setBooks(newArr)
}
});
}
else //this book does not contain an image
++dataWithoutImage
})
检查分辨率的函数如下所示:
let mypromise = function checkImageResolution(url) {
return new Promise((resolve, reject) => {
var img = new Image();
img.src = url;
img.onload = function () {
console.log("image dimensions", this.width, this.height);
if (this.width < 125 || this.height < 100) //if either of these is true, reject the image
reject("low quality image");
else
resolve("high quality ,let's have this one");
}
});
}