API返回图片显示异常:如何将result中的图片在新标签页打开?
解决YouTube缩略图API返回图片无法在新标签页显示的问题
你的代码核心问题是错误地用response.text()处理图片二进制数据,这会把原始二进制流转成UTF-8字符串,破坏图片的原始结构,自然无法正常显示。下面是修正后的实现方案:
修正后的代码
async function scan() { const url = "https://youtube-thumbnail-downloader1.p.rapidapi.com/api/Thumbnail/GetThumbnail?youtubeLink=https%3A%2F%2Fyoutu.be%2Fjw0F5UFImfY"; const options = { method: "GET", headers: { "X-RapidAPI-Key": "b54739a76emsh4acae4b362f10a7p17b7d8jsn58665918e429", "X-RapidAPI-Host": "youtube-thumbnail-downloader1.p.rapidapi.com", }, }; try { const response = await fetch(url, options); // 关键:用blob()接收二进制图片数据,而非text() const imageBlob = await response.blob(); // 创建浏览器可识别的图片临时URL const imageUrl = URL.createObjectURL(imageBlob); // 在新标签页打开图片 window.open(imageUrl); // 可选:若需在当前页面插入图片,可使用以下代码 // const img = document.createElement('img'); // img.src = imageUrl; // document.body.appendChild(img); // 可选:手动释放临时URL,避免内存泄漏(浏览器也会自动回收) // setTimeout(() => URL.revokeObjectURL(imageUrl), 5000); } catch (error) { console.error(error); } } scan();
关键说明
response.blob():专门用于处理图片、音频这类二进制文件,能完整保留原始数据结构。URL.createObjectURL():将Blob对象转换为浏览器可直接加载的临时URL,支持在新标签页或img元素中使用。- 临时URL释放:如果不需要长期保留图片资源,调用
URL.revokeObjectURL()可以主动释放内存,优化性能。
内容的提问来源于stack exchange,提问作者Pratham Singh
相关产品推荐
相关产品推荐

