Ruloaooa commited on
Commit
ae3902d
·
verified ·
1 Parent(s): 44cee83

Create loader.js

Browse files
Files changed (1) hide show
  1. loader.js +39 -0
loader.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const fetch = require('node-fetch'); // Pastikan ini diinstal
4
+ const { Image } = require('canvas');
5
+
6
+ // Fungsi untuk memuat gambar dari URL atau jalur file lokal
7
+ async function loadImg(source) {
8
+ try {
9
+ // Cek apakah sumber adalah URL
10
+ const isUrl = /^https?:\/\//.test(source);
11
+
12
+ if (isUrl) {
13
+ // Jika URL, ambil gambar menggunakan fetch
14
+ const response = await fetch(source);
15
+ if (!response.ok) {
16
+ throw new Error(`Gagal memuat gambar dari URL: ${response.statusText}`);
17
+ }
18
+ const buffer = await response.buffer();
19
+ const img = new Image();
20
+ img.src = buffer;
21
+ return img;
22
+ } else {
23
+ // Jika jalur lokal, baca file secara sinkron
24
+ const filePath = path.resolve(source); // Resolusi jalur absolut
25
+ if (!fs.existsSync(filePath)) {
26
+ throw new Error(`File tidak ditemukan di jalur: ${filePath}`);
27
+ }
28
+ const buffer = fs.readFileSync(filePath);
29
+ const img = new Image();
30
+ img.src = buffer;
31
+ return img;
32
+ }
33
+ } catch (error) {
34
+ console.error(`Error loading image (${source}):`, error.message);
35
+ throw error;
36
+ }
37
+ }
38
+
39
+ module.exports = loadImg