问题描述
我有一个Angular应用程序,我需要Base64编码图像的尺寸。
我试图将它加载到 Image
但它只是说它是 0x0
I have an Angular application where i need the dimensions of an Base64 encoded image.I have tried to load it into an Image
but it just says it is 0x0
const image = new Image();
image.src = 'data:image/jpeg;base64,someBase64ImageString';
console.log(image.width + 'x' + image.height);
我无法弄清楚如何获取这些信息。
I cannot figure out how to get this information.
推荐答案
设置 src
和处于已加载状态(因此具有维度)的图像之间的步骤是异步的 - 这似乎适用于数据URI和外部资源(至少在Chrome中)。
The step between setting the src
and the image being in a "loaded" state (thus having dimensions) is asynchronous - this seems to apply to data URIs as well as external resources (at least in Chrome).
为了安全地保证宽度$ c填充$ c>和
height
,逻辑应该在回调中运行
- 即
To safely guarantee the width
and height
are populated, logic should be run in a callback - i.e.
let im = new Image;
im.src = 'data:image/png;base64,whatever';
im.onload = () => console.log(im.width);
请注意,这只是第一次加载图片时的问题,您的代码按原样运行连续调用 - 这可能与浏览器处理和缓存数据的方式有关。
Note this is only an issue the first time an image is loaded, your code works as-is for successive calls - presumable this has something to do with the way the browser is processing and caching the data.
这篇关于从Base64编码图像获取尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!