为了在没有外部库的情况下获得图像的宽度和高度,您需要解析图像标题.如果您只处理几种图像类型,您可以很容易地避免使用第三方库.
例如,要从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
宽度和高度提供以像素为单位的图像尺寸.它们是4字节的
整数.零是无效值.每个的最大值是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之后)
自己检测jpeg请参见https://github.com/sindresorhus/file-type/blob/5c42f8057f056fe41cbe4bffb53f56987d02e909/core.js#L238-L249.
根据您处理的图像类型的不同,它可能会更加复杂,如果您支持多种图像格式,我建议您使用诸如sharp
这样的库来解析数据.