typescript - 如何在 deno 中获取 Base64 图像的宽度/高度?

标签 typescript supabase deno

这是这个问题的重复:Get image width and height from the Base64 code in JavaScript但我问的是关于 deno 的问题。 Deno 没有我读过的所有解决方案中使用的 new Image() 。我打算在边缘函数中执行此操作,因此减少依赖性很重要。我考虑过的一些事情:

有没有办法在没有包的情况下做到这一点,或者只使用一些内置包来做到这一点?

最佳答案

为了在没有外部库的情况下获取图像的宽度和高度,您需要解析图像头。如果您只处理少数图像类型,您可以轻松避免使用第三方库。

例如,要从 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/

相关文章:

javascript - 在 Angular 4 中实现 d3.js

typescript - 如何在 VSCode 扩展中检测 TypeScript 初始化时间?

javascript - 有没有办法以编程方式更改激活的 mat-tab?

react-native - 在 native react 中使用 supabase 时保持用户登录

javascript - 如何降级 Deno

javascript - 如何在 typescript 中正确编写条件 promise.resolve?

sveltekit - 有没有办法删除以前的 session 而不需要硬刷新(sveltekit 和 Supabase)

javascript - 我可以通过 Firebase 对用户进行身份验证并使用 Supabase(私有(private))存储桶而不依赖 Supabase 身份验证用户限制吗

typescript - 我在哪里可以看到 deno 下载的软件包?

deno - 将脚本通过管道传输到 deno run