UNPKG

@blocklet/images

Version:

support functions for blocklet image validation

44 lines (43 loc) 1.71 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getBlurhash = getBlurhash; const fs_1 = __importDefault(require("fs")); const jimp_1 = require("jimp"); const utils_1 = require("@jimp/utils"); const blurhash_1 = require("blurhash"); const image_type_1 = __importDefault(require("image-type")); const is_svg_1 = __importDefault(require("is-svg")); async function getBlurhash(filePath) { if (!fs_1.default.existsSync(filePath)) { throw new Error(`File not found: ${filePath}`); } const buffer = fs_1.default.readFileSync(filePath); const type = (0, image_type_1.default)(buffer); if (!type) { // svg 转位图 if ((0, is_svg_1.default)(buffer)) { // return empty blurhash return ''; } throw new Error(`File is not a valid image: ${filePath}`); } // Read image using Jimp const image = await jimp_1.Jimp.read(buffer); const { width, height } = image.bitmap; // Convert image data to RGBA array const pixels = new Uint8ClampedArray(width * height * 4); // Scan through each pixel and add to array image.scan(0, 0, width, height, (x, y) => { const pixelIndex = (y * width + x) * 4; const rgba = (0, utils_1.intToRGBA)(image.getPixelColor(x, y)); pixels[pixelIndex] = rgba.r; pixels[pixelIndex + 1] = rgba.g; pixels[pixelIndex + 2] = rgba.b; pixels[pixelIndex + 3] = rgba.a; }); const blurhash = (0, blurhash_1.encode)(pixels, width, height, 4, 4); return blurhash; }