const fs = require('fs'); const path = require('path'); const fetch = require('node-fetch'); // Pastikan ini diinstal const { Image, loadImage } = require('canvas'); // Fungsi untuk memuat gambar dari URL atau jalur file lokal async function loadImg(source) { try { // Cek apakah sumber adalah URL const isUrl = /^https?:\/\//.test(source); if (isUrl) { // Jika URL, ambil gambar menggunakan fetch const response = await fetch(source); if (!response.ok) { throw new Error(`Gagal memuat gambar dari URL: ${response.statusText}`); } const buffer = await response.buffer(); const img = new Image(); img.src = buffer; return img; } else { // Jika jalur lokal, baca file secara sinkron const filePath = path.resolve(source); // Resolusi jalur absolut if (!fs.existsSync(filePath)) { throw new Error(`File tidak ditemukan di jalur: ${filePath}`); } const buffer = await fs.promises.readFile(filePath); // Baca file secara async const img = new Image(); img.src = buffer; // Gunakan buffer untuk mengatur sumber return img; } } catch (error) { console.error(`Error loading image (${source}):`, error.message); throw error; } } module.exports = loadImg