The isValidImage
function is used to check whether an image file is valid or not. It accepts a Buffer as an argument.
You can also pass an options object as a second argument to exclude a specific type.
import { isValidImage } from 'multiform-validator';
import ImageBuffer from 'image-buffer';
const buffer: Buffer = ImageBuffer;
const isValid = isValidImage(buffer);
console.log(isValid); // true if the image is valid, false otherwise
Passing options to the isValidImage
import { isValidImage } from 'multiform-validator';
import ImageBuffer from 'image-buffer';
const buffer: Buffer = ImageBuffer;
const isValid = isValidImage(buffer, { exclude: ['gif'] });
console.log(isValid); // true if the image is valid, false otherwise
In this example it only allocates 4 bytes for performance reasons, but you can pass the entire file.
const filePath = resolve(process.cwd(), 'public', 'assets', 'images');
const fileGetted = resolve(filePath, filename);
const buffer = Buffer.alloc(4);
const fd = fs.openSync(fileGetted, 'r');
fs.readSync(fd, buffer, 0, 4, 0);
fs.closeSync(fd);
const isValidImageResult = isValidImage(buffer);
if (!isValidImageResult) {
fs.unlinkSync(fileGetted);
throw new BadRequestException('Invalid image');
}
First, import the isValidImage
function from 'multiform-validator'. Then, define the path to the image you want to check. Call the isValidImage
function with the image path as an argument. The function will return true
if the image is valid and false
if it is not.