使用 JavaScript File API 获取图像尺寸
我需要在我的网络应用程序中生成图像的缩略图。我使用 HTML5 File API 生成缩略图。
我使用了在 JavaScript 中读取文件 生成缩略图。
我能够成功生成缩略图,但我只能通过使用静态大小来生成缩略图。有没有办法从所选文件中获取文件尺寸,然后创建 Image 对象?
I require to generate a thumbnail of an image in my web application. I make use of the HTML5 File API to generate the thumbnail.
I made use of the examples from Read files in JavaScript to generate the thumbnails.
I am successfully able to generate the thumbnails, but I am able to generate thumbnail only by using a static size. Is there a way to get the file dimensions from the selected file and then create the Image object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,将文件作为数据 URL 读取,并将该数据 URL 传递到
Image
的src
:http://jsfiddle.net/pimvdb/eD2Ez/2/。Yes, read the file as a data URL and pass that data URL to the
src
of anImage
: http://jsfiddle.net/pimvdb/eD2Ez/2/.或者使用对象 URL:http://jsfiddle.net/8C4UB/
Or use an object URL: http://jsfiddle.net/8C4UB/
现有的答案对我帮助很大。然而,由于
img.onload
事件导致的奇怪的事件顺序让我的事情变得有点混乱。所以我调整了现有的解决方案,并将它们与基于承诺的方法结合起来。下面是一个函数,返回一个带有维度作为对象的 Promise:
下面是如何将它与异步函数一起使用:
下面是如何使用
then()
语法来使用它:The existing answers helped me a lot. However, the odd order of events due to the
img.onload
event made things a little messy for me. So I adjusted the existing solutions and combined them with a promise-based approach.Here is a function returning a promise with the dimensions as an object:
Here is how you could use it with an async function:
And here is how you could use it using the
then()
syntax:我已将 pimvdb 的答案 包装在一个函数中在我的项目中通用:
I have wrapped pimvdb's answer in a function for general-purpose use in my project:
没什么花哨的,也能完成工作。
Nothing fancy and does the job.