這裏是我的代碼:如何獲得網絡工作者的圖像寬度和高度?
// process-image.js (web-worker)
self.addEventListener('message', ev => {
const {id,file} = ev.data;
const reader = new FileReader();
reader.onload = ev => {
const imageFile = new Image(); // <-- error is here
imageFile.src = ev.target.result;
imageFile.onload =() => {
const fit = makeFit(imageFile);
self.postMessage({
id,
file: {
src: ev.target.result,
width: fit.width,
height: fit.height,
}
})
}
};
reader.readAsDataURL(file);
});
這是在主UI線程工作正常,但顯然我沒有Image
一個網絡工作者的內部訪問。具體的錯誤是:
Uncaught ReferenceError: Image is not defined at FileReader.reader.onload (process-image.js:12)
有沒有另一種方式獲取圖像的寬度和高度?
我想支持儘可能多的文件類型,但是如果有某種類型的庫可以執行此操作並且將在網絡工作者中運行,那麼現在只需要JPG即可。
下面是從UI線程的相關位:
// some-react-component.js
componentDidMount() {
this.worker = new ImageWorker();
this.worker.addEventListener('message', ev => {
const {id, file} = ev.data;
this.setState(({files}) => {
files = files.update(id, img => ({
...img,
...file,
}))
const withWidths = files.filter(f => f.width);
const avgImgWidth = withWidths.reduce((acc, img) => acc + img.width, 0)/withWidths.size;
return {files, avgImgWidth};
});
});
}
onDrop = ev => {
ev.preventDefault();
Array.prototype.forEach.call(ev.dataTransfer.files, file => {
const id = shortid();
this.worker.postMessage({id, file});
const img = {
id,
width: null,
height: null,
src: null,
name: file.name,
}
this.setState(({files}) => ({files: files.set(id, img)}));
});
}
唯一這裏值得注意的是,id
只是一個隨機UUID,並file
是File
。我將整件事傳遞給網絡工作者,以便我可以在那裏完成所有的處理。
Awww yes! 'createImageBitmap'看起來像我正在尋找的。甚至可能幫助調整大小,這是我的下一個任務。請儘快試用,謝謝! – mpen
對不起,複製粘貼真正快速發佈答案,將編輯,謝謝! – PiniH