javascript-binary-converter
Version:
A utility package to quickly handle and convert various Javascript binary objects
57 lines • 2.06 kB
JavaScript
export async function binaryToImage(binary, config) {
let finalBinary;
if (config?.maxSize) {
finalBinary = await getBlobWithModifiedImageSize(binary, { maxSize: config.maxSize });
}
else {
finalBinary = binary;
}
const image = new Image();
image.src = URL.createObjectURL(finalBinary);
await new Promise((res) => image.onload = res);
return image;
}
export async function getBlobWithModifiedImageSize(binary, config) {
const image = new Image();
image.src = URL.createObjectURL(binary);
await new Promise((res) => image.onload = res);
const deducedDimensions = getScaledDimensions({ width: image.width, height: image.height, maxSize: config.maxSize });
const blob = await imageToBlob(image, deducedDimensions);
return blob;
}
/**
* Reduce the dimensions of an image, while maintaining its ratio.
*/
export function getScaledDimensions({ width: w, height: h, maxSize }) {
let width = w;
let height = h;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
}
else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
return { width, height };
}
export async function imageToBlob(image, config) {
const height = config?.height || image.height;
const width = config?.width || image.width;
const type = config?.type || 'image/png';
const canvas = imageToCanvas(image, { height, width });
const blob = await new Promise((res) => canvas.toBlob(res, type));
return blob;
}
export function imageToCanvas(image, config) {
const canvas = document.createElement("canvas"); //Create a canvas, in order to get Blob from the original image.
canvas.width = config.width;
canvas.height = config.height;
canvas.getContext('2d').drawImage(image, 0, 0, config.width, config.height);
return canvas;
}
//# sourceMappingURL=image.js.map