From bdb6397a5f05f3ddfdbdd9f8c6b27200a5044f02 Mon Sep 17 00:00:00 2001 From: Peter Muriuki Date: Wed, 20 Nov 2024 13:44:26 +0300 Subject: [PATCH] Validate image is < 5mb and compress --- .../components/CommodityAddEdit/Eusm/utils.ts | 24 ++++++++++++++++++- .../src/components/ProductForm/index.tsx | 1 + .../src/components/ProductForm/utils.tsx | 18 +++++++++++++- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/packages/fhir-group-management/src/components/CommodityAddEdit/Eusm/utils.ts b/packages/fhir-group-management/src/components/CommodityAddEdit/Eusm/utils.ts index 9d4e22f4c..7d12f7035 100644 --- a/packages/fhir-group-management/src/components/CommodityAddEdit/Eusm/utils.ts +++ b/packages/fhir-group-management/src/components/CommodityAddEdit/Eusm/utils.ts @@ -52,6 +52,8 @@ import { UploadFile } from 'antd'; import { Coding } from '@smile-cdr/fhirts/dist/FHIR-R4/classes/coding'; import { R4GroupTypeCodes } from '@opensrp/fhir-helpers'; import { defaultValidationRulesFactory } from '../../ProductForm/utils'; +import { RcFile } from 'antd/es/upload'; +import imageCompression from 'browser-image-compression'; export type EusmGroupFormFields = GroupFormFields<{ group: IGroup; binary?: IBinary }>; @@ -282,6 +284,23 @@ function fileToBase64(file?: File): Promise { }); } +/** + * Compresses images before uploading, images is scaled down and + * converted to webp format + * + * @param file - image file to be downscaled + */ +export async function compressImage(file: RcFile | undefined) { + if (!file) return; + const options = { + maxSizeMB: 1, + maxWidthOrHeight: 1920, + fileType: 'image/webp', + }; + const compressedBlob = await imageCompression(file, options); + return compressedBlob; +} + /** * generates the binary payload for uploaded image * @@ -298,6 +317,9 @@ export async function getProductImagePayload( const currentImageb64 = await fileToBase64(currentImage); const initialImageb64 = await fileToBase64(initialImage); + const scaledDownImage = await compressImage(currentImage); + const scaledDownCurrentImageb64 = await fileToBase64(scaledDownImage); + if (currentImageb64 === initialImageb64) { // This could mean it was not added or removed. return { @@ -313,7 +335,7 @@ export async function getProductImagePayload( id, resourceType: binaryResourceType, contentType: currentImage.type, - data: currentImageb64, + data: scaledDownCurrentImageb64, }; return { changed: true, diff --git a/packages/fhir-group-management/src/components/ProductForm/index.tsx b/packages/fhir-group-management/src/components/ProductForm/index.tsx index 2f4dba13e..30ac1ef5d 100644 --- a/packages/fhir-group-management/src/components/ProductForm/index.tsx +++ b/packages/fhir-group-management/src/components/ProductForm/index.tsx @@ -278,6 +278,7 @@ function CommodityForm< {({ getFieldValue }) => { return (