Ruloaooa commited on
Commit
e0f9ab7
·
verified ·
1 Parent(s): 39f375e

Update loader.js

Browse files
Files changed (1) hide show
  1. loader.js +18 -15
loader.js CHANGED
@@ -1,36 +1,39 @@
1
- const { createCanvas, loadImage } = require('canvas');
2
  const fs = require('fs');
3
  const path = require('path');
4
- const fetch = require('node-fetch');
 
5
 
6
- const loadImg = async (source) => {
 
7
  try {
8
- // Cek apakah source adalah URL
9
  const isUrl = /^https?:\/\//.test(source);
10
 
11
- let img;
12
  if (isUrl) {
13
- // Jika source adalah 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(); // Ambil gambar dalam bentuk buffer
19
- img = await loadImage(buffer); // Load gambar menggunakan canvas.loadImage
 
 
20
  } else {
21
- // Jika source adalah file lokal, baca gambar dari sistem file
22
- const filePath = path.resolve(source);
23
  if (!fs.existsSync(filePath)) {
24
  throw new Error(`File tidak ditemukan di jalur: ${filePath}`);
25
  }
26
  const buffer = fs.readFileSync(filePath);
27
- img = await loadImage(buffer); // Load gambar dari buffer file
 
 
28
  }
29
- return img; // Kembalikan gambar
30
  } catch (error) {
31
- console.error(`Error loading image from ${source}:`, error.message);
32
- throw error; // Lempar error jika gagal
33
  }
34
- };
35
 
36
  module.exports = loadImg
 
 
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