@topgroup/diginext
Version:
A BUILD SERVER & CLI to deploy apps to any Kubernetes clusters.
72 lines (71 loc) • 2.31 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getImageDimensions = exports.downloadImage = exports.getImageBufferFromUrl = exports.readFileToBuffer = void 0;
const axios_1 = __importDefault(require("axios"));
const fs_1 = require("fs");
const image_size_1 = __importDefault(require("image-size"));
const path_1 = __importDefault(require("path"));
function readFileToBuffer(filePath) {
const _path = path_1.default.resolve(filePath);
try {
const buffer = (0, fs_1.readFileSync)(_path);
return buffer;
}
catch (err) {
throw new Error(`Error reading file from path ${filePath}: ${err.message}`);
}
}
exports.readFileToBuffer = readFileToBuffer;
/**
* Read image url and convert to {Buffer}
*/
async function getImageBufferFromUrl(url) {
try {
const response = await axios_1.default.get(url, { responseType: "arraybuffer" });
return Buffer.from(response.data);
}
catch (error) {
console.error("Error fetching the image:", error);
return;
}
}
exports.getImageBufferFromUrl = getImageBufferFromUrl;
/**
* Download image from input URL
*/
async function downloadImage(url, outputPath) {
try {
const response = await axios_1.default.get(url, {
responseType: "arraybuffer",
});
(0, fs_1.writeFileSync)(outputPath, response.data);
// console.log(`Image downloaded and saved to ${outputPath}`);
return outputPath;
}
catch (error) {
console.error("Error downloading the image:", error);
return;
}
}
exports.downloadImage = downloadImage;
/**
* Get image's dimentions (width, height)
* @param url - Input image URL
*/
async function getImageDimensions(url) {
try {
const buffer = await getImageBufferFromUrl(url);
if (!buffer)
throw new Error(`Unable to read image from url.`);
const dimensions = (0, image_size_1.default)(buffer);
return dimensions;
}
catch (error) {
console.error("Error fetching the image:", error);
return null;
}
}
exports.getImageDimensions = getImageDimensions;