如何刷新XMLHttpRequest获取Blob图片并设置图片宽高
解决方案:自动刷新摄像头图片与设置图片宽高
一、自动刷新XMLHttpRequest获取新图片
你当前用setTimeout只会执行一次请求,要实现周期性获取新图片,应该用setInterval定时触发请求。另外每次创建ObjectURL后,记得销毁旧的URL避免内存泄漏。
修改后的请求逻辑示例:
// 全局变量存储定时器和旧图片URL let refreshTimer; let oldImageUrl = null; function fetchNewImage() { const xhr = new XMLHttpRequest(); xhr.open("GET", "http://192.168.1.186:8080/dwkpic.html", true); xhr.responseType = "arraybuffer"; xhr.onload = function(e) { const arrayBufferView = new Uint8Array(this.response); const blob = new Blob([arrayBufferView], { type: "image/jpeg" }); const urlCreator = window.URL || window.webkitURL; const imageUrl = urlCreator.createObjectURL(blob); const img = document.querySelector("#photo"); // 销毁旧URL释放内存 if (oldImageUrl) { urlCreator.revokeObjectURL(oldImageUrl); } img.src = imageUrl; oldImageUrl = imageUrl; }; // 处理请求失败场景 xhr.onerror = function() { console.error("获取图片失败"); }; xhr.send(); } // 启动定时刷新,间隔可按需调整(示例为2秒) refreshTimer = setInterval(fetchNewImage, 2000); // 页面卸载时清理资源 window.addEventListener("beforeunload", function() { clearInterval(refreshTimer); if (oldImageUrl) { (window.URL || window.webkitURL).revokeObjectURL(oldImageUrl); } });
二、设置Blob对应图片的宽高
设置图片宽高有两种常用方式:
1. 固定宽高(直接设置)
像你代码里那样直接给img元素设置属性,或通过CSS控制,适合需要固定尺寸的场景:
// 在替换src后设置 img.width = 400; img.height = 400; // 也可用CSS方式 // img.style.width = "400px"; // img.style.height = "400px";
2. 按原图比例自适应
如果希望保持图片原始比例,可等图片加载完成后计算设置:
img.onload = function() { // 示例:固定宽度,高度按比例计算 const targetWidth = 400; const ratio = targetWidth / this.naturalWidth; this.width = targetWidth; this.height = this.naturalHeight * ratio; };
整合后的完整代码
结合两个需求的最终代码:
<!DOCTYPE html> <html> <body> <img id="photo" /> <script> let refreshTimer; let oldImageUrl = null; function fetchNewImage() { const xhr = new XMLHttpRequest(); xhr.open("GET", "http://192.168.1.186:8080/dwkpic.html", true); xhr.responseType = "arraybuffer"; xhr.onload = function(e) { const arrayBufferView = new Uint8Array(this.response); const blob = new Blob([arrayBufferView], { type: "image/jpeg" }); const urlCreator = window.URL || window.webkitURL; const imageUrl = urlCreator.createObjectURL(blob); const img = document.querySelector("#photo"); if (oldImageUrl) { urlCreator.revokeObjectURL(oldImageUrl); } img.src = imageUrl; oldImageUrl = imageUrl; // 启用固定宽高 img.width = 400; img.height = 400; // 如需自适应比例,注释上面两行,打开下面代码 // img.onload = function() { // const targetWidth = 400; // const ratio = targetWidth / this.naturalWidth; // this.width = targetWidth; // this.height = this.naturalHeight * ratio; // }; }; xhr.onerror = function() { console.error("获取图片失败"); }; xhr.send(); } // 每2秒刷新一次 refreshTimer = setInterval(fetchNewImage, 2000); window.addEventListener("beforeunload", function() { clearInterval(refreshTimer); if (oldImageUrl) { (window.URL || window.webkitURL).revokeObjectURL(oldImageUrl); } }); // 页面加载时先获取一次图片 fetchNewImage(); </script> </body> </html>
内容的提问来源于stack exchange,提问作者dwk
相关产品推荐
相关产品推荐

