@fukayatti0/discord-rpc
Version:
a fork of discordjs/RPC
38 lines (37 loc) • 1.48 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.padImageUrlToSquare = padImageUrlToSquare;
const sharp_1 = __importDefault(require("sharp"));
/**
* 指定URLの画像をダウンロードし、1:1の正方形PNG(上下透明パディング)に加工してBufferで返す
* @param imageUrl 画像URL
* @param size 正方形の一辺のピクセル数
* @returns 加工済み画像のBuffer
*/
async function padImageUrlToSquare(imageUrl, size) {
const res = await fetch(imageUrl);
if (!res.ok)
throw new Error("画像のダウンロードに失敗しました");
const arrayBuffer = await res.arrayBuffer();
const inputBuffer = Buffer.from(arrayBuffer);
// 画像を横幅基準でリサイズ
const image = (0, sharp_1.default)(inputBuffer).resize({ width: size });
const metadata = await image.metadata();
const newHeight = Math.round((metadata.height ?? 0) * (size / (metadata.width ?? 1)));
const topPad = Math.floor((size - newHeight) / 2);
const bottomPad = size - newHeight - topPad;
return await image
.resize(size, newHeight)
.extend({
top: topPad,
bottom: bottomPad,
left: 0,
right: 0,
background: { r: 0, g: 0, b: 0, alpha: 0 }
})
.png()
.toBuffer();
}