File size: 1,293 Bytes
ae3902d
 
e0f9ab7
80fcdcb
ae3902d
e0f9ab7
 
ae3902d
e0f9ab7
ae3902d
 
 
e0f9ab7
ae3902d
 
 
 
e0f9ab7
 
 
 
ae3902d
e0f9ab7
 
ae3902d
 
 
9af3c03
 
 
e0f9ab7
ae3902d
 
e0f9ab7
 
ae3902d
e0f9ab7
ae3902d
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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