Skip to content
This repository was archived by the owner on Oct 28, 2023. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/util/image-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,29 @@ const base64Image = async (file: string) => {
// read binary data
const bitmap = await readFile(file);
// convert binary data to base64 encoded string
cache[file] = Buffer.from(bitmap).toString('base64');
return cache[file];
return Buffer.from(bitmap).toString('base64');
};

const downloadBase64Image = async (url: string) => {
// convert to base64 encoded string
const res = await axios.get(url, { responseType: 'arraybuffer' });
// cache the result
cache[url] = Buffer.from(res.data).toString('base64');
return cache[url];
return Buffer.from(res.data).toString('base64');
};

// Convert url or file image to Base64 String
export const imageToBase64 = async (image: string, useCache = false) => {
if (useCache && cache[image]) {
return cache[image];
}

let imageBase64: string;
const [, type] = (mime.lookup(image.replace(/\?.+$/, '')) || '').split('/');
if (image.startsWith('http')) {
image = await downloadBase64Image(image);
imageBase64 = await downloadBase64Image(image);
} else {
image = await base64Image(image);
imageBase64 = await base64Image(image);
}
return `data:image/${type};base64, ${image}`;

cache[image] = `data:image/${type};base64, ${imageBase64}`;
return cache[image];
};