这是这个问题的重复:Get image width and height from the Base64 code in JavaScript但我问的是关于 deno 的问题。 Deno 没有我读过的所有解决方案中使用的 new Image() 。我打算在边缘函数中执行此操作,因此减少依赖性很重要。我考虑过的一些事情:
- https://github.com/DjDeveloperr/skia_canvas 但我正在工作的边缘环境不允许使用此功能所需的写入访问权限。
- https://github.com/matmen/ImageScript 但我不知道从中导入它的相关 deno http 地址
有没有办法在没有包的情况下做到这一点,或者只使用一些内置包来做到这一点?
最佳答案
为了在没有外部库的情况下获取图像的宽度和高度,您需要解析图像头。如果您只处理少数图像类型,您可以轻松避免使用第三方库。
例如,要从 Base64 编码图像中解析 png 图像宽度和高度,您可以这样做:
import { decode } from "https://deno.land/std/encoding/base64.ts"
const pngImageb64 = /* some png image in base64 */
const pngImage = decode(pngImageb64);
const dataView = new DataView(pngImage.buffer);
// The width and height are 4-byte integers starting
// at byte offset 16 and 20, respectively.
const width = dataView.getUint32(16);
const height = dataView.getUint32(20);
引用号:http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
Width and height give the image dimensions in pixels. They are 4-byte integers. Zero is an invalid value. The maximum for each is 2^31
对于 jpeg 来说有点困难,因为尺寸存储在帧开始 (SOF) 标记中。以下应该适用于大多数情况(仅在一些 jpeg 中进行了测试)
const jpegImageb64 = /* some jpeg image in base64 */
const jpegImage = decode(jpegImageb64);
const dataView = new DataView(jpegImage.buffer);
let width, height;
for (let i = 0; i < dataView.byteLength - 9; i++) { // - 9 prevent out-of-bounds access
if (dataView.getUint16(i) === 0xFFC0 || dataView.getUint16(i) === 0xFFC2) {
height = dataView.getUint16(i + 5);
width = dataView.getUint16(i + 7);
break;
}
}
其他可能的解决方案:
要检测图像类型以便知道要使用哪个解析器,您必须读取图像的第一个字节,可以使用 file-type
它的lib(解码base64后)
参见https://github.com/sindresorhus/file-type/blob/5c42f8057f056fe41cbe4bffb53f56987d02e909/core.js#L238-L249用于自己检测 jpeg。
根据您正在处理的图像类型,它可能会更复杂,如果您支持多种图像格式,我建议使用诸如 sharp
之类的库来解析该数据。
关于typescript - 如何在 deno 中获取 Base64 图像的宽度/高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77424794/