图像预览和网络工作者
是否可以在 Web Worker 中使用 filereader api 来加载图像(即预览/缩略图),从而防止主 ui 线程阻塞。
类似于 this 但包装了 cpu 密集型部分(主要是读取文件内容和缩放图像)在网络工作者内部
Is it possible to use the filereader api within a web worker to load images i.e. for previews/thumbails, therefore preventing the main ui thread from blocking.
Something like this but wrapping the cpu intensive parts (mainly reading the files contents and scaling the image) inside a web worker
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从工作人员那里不可能访问页面的 DOM 级别,因此您无法创建 Image 对象或画布(用于缩放部分),因此答案是否定的,因为您想要操作图像。
虽然可以通过 ajax 或 FileReaderSync 在 Web Worker 上加载图像文件,将其转换为 Base64 数据 url 字符串并将其发送回主脚本,但无法进行操作图像以创建缩略图。 (除非您知道 png/jpg/bmp 格式的文件规范并且想要硬编码直接在二进制字符串上工作的缩放函数,否则看起来不太好吧?)
From a worker it's not possible to access the page's DOM level so you can't create an Image object or a canvas (for the scaling part) so the answer is no since you want to manipulate the image.
It is possible though to load the image files on a web worker via ajax or the
FileReaderSync
, convert it to a base64 data url string and send it back to the main script, but there is no way to manipulate the image in order to create your thumbnails. (unless you know the file spec for png/jpg/bmp formats and want to hardcode a scaling function working directly on the binary string, doesn't look so good huh?)主线程称为 UI 线程,因为与 UI 直接相关的所有事情都必须在那里发生。您无法在 Web Worker 中操作 DOM,但可以在 Web Worker 中操作图像文件的二进制文件。图像操作完成后,您必须将数据传输到主线程并让它附加到 DOM。然后浏览器将在主线程中渲染该图像。
The main thread is called UI thread because everything related to the UI directly has to happen there. You can't manipulate DOM in Web Worker but you can manipulate binary of the image file within the Web Worker. After image manipulation, you have to transfer the data to the main thread and let it attach it to the DOM. The browser then will render this image within main thread.
如果可以的话,这是可能的。
需要阅读的内容:发送数组缓冲区、可传输对象
写下整个脚本就超出了范围。
It is possible, if you can.
Something to read:Sending Arraybuffer, Transferable Objects
To write down the whole script would go beyond the scope.