Crop images using LWC and External JS library !

Pradeep Hegde
Cloudwerx
Published in
3 min readMay 4, 2022

Introduction:

In today’s world, adaptability and customization are something that everyone wants to achieve. Similarly, small tricks and flicks help one's capability of getting things done on time. These tricks turn out to be a lifesaver in terms of functionality and also contribute to saving a lot of time for everyone.

In this blog, we are going to learn about cropping an image using LWC and the External JS library (Croppie).

Crop images when uploading !

Implementation steps :

Step 1 :

Upload static resources shown below in your org which are available on Croppie website.

Step 2 :

Let's create an LWC component !

Use the snippet below for Croppie
Croppie.Html

<template if:true="{croppieLoaded}">
<div data-id="custom" class="imge-cropping"></div>
<div class="slds-form-element slds-m-vertical_large">
<div class="slds-form-element__control">
<div class="slds-file-selector slds-file-selector_files">
<div class="slds-file-selector__dropzone">
<input type="file" class="slds-file-selector__input slds-assistive-text" accept=".png, .jpg, .jpeg" id="img-crop-input" />
<label class="slds-file-selector__body" for="img-crop-input">
<span class="slds-file-selector__button slds-button">
<lightning-icon icon-name="doctype:image" size="large" alternative-text="Upload Picture" class="slds-m-right_large"></lightning-icon>
<div class="image-info">
<h3 class="slds-tile__title slds-truncate slds-m-bottom_none">{displayfileName}</h3>
<p>{fileSizeInMb} Mb</p>
</div>
</span>
</label>
</div>
</div>
</div>
</div>
</template>

Croppie.JS

Import the static resources loaded by you in your org into your JS using the below snippet :

import cropCss from '@salesforce/resourceUrl/croppieCss';import cropJS from '@salesforce/resourceUrl/croppieJs';

Let's invoke the Croppie using the following snippet

Promise.all([
loadStyle(this, cropCss),
loadScript(this, cropJS)
]).then(() => {}).catch(error => {
console.log('Error occurred');
});

Set the parameters for Croppie to load by using the following snippet :

reader.Onload = () => {
this.fileDetailReader = new Croppie(this.template.querySelector('[data-id="custom"]'), {
viewport: {
width: 199,
height: 199,
type: 'circle'
},
boundary: {
width: 200,
height: 200
},
showZoomer: true,
});
this.fileDetailReader.bind({
url: reader.result
});
this.fileName = file.name;
}
reader.readAsDataURL(file)

Get details of the cropped image using following snippet :

this.fileDetailReader.result({
type: 'base64'
}).then(result => {
this.fileData = result.split(',')[1];
insertProfilePic({
filename: this.fileName,
filebase: this.fileData,
recordid: this.recordId
}).then(result => {
if (result.successRespObj) {
this.hideSpinner();
this.photoUrlGenerated = result.successRespObj;
const uploadedPhoto = new CustomEvent('photouploaded', {
detail: {
photoUrl: this.photoUrlGenerated,
type: 'save',
uploaded: true
}
});
this.dispatchEvent(uploadedPhoto);
} else {
console.log('Error occurred);
}
})
.catch(error => {
console.log('Error occurred');
}
});
});

Now you are good to upload and crop your pic in Salesforce.

Apex class :

CroppieCtrl.cls

@AuraEnabled
public static String insertProfilePic(String filename, String filebase, String recordid) {
ContentVersion cVersion = new ContentVersion();
cVersion.ContentLocation = 'S';
cVersion.PathOnClient = filename;
cVersion.Title = filename;
cVersion.VersionData = EncodingUtil.base64Decode(filebase);
cVersion.IsMajorVersion = true;
Insert cVersion;
ContentVersion conDocument = // query contentDocumentId related to contentVersion inserted above.
ContentDocumentLink cDocLink = new ContentDocumentLink();
cDocLink.ContentDocumentId = conDocument.ContentDocumentId;
cDocLink.LinkedEntityId = recordId;
cDocLink.Visibility = 'AllUsers';
Insert cDocLink;
ContentVersion ContentVersionIdList = // query contentVersionId from contentDocument
ContentDistribution cdl = new ContentDistribution();
cdl.ContentVersionId = ContentVersionIdList.Id;
cdl.Name = 'PublicShare';
cdl.PreferencesNotifyOnVisit = false;
insert cdl;
ContentDistribution cdlink = //get downladable url by querying the content Distribution
List <Account> accConId = AccountDomain.getPersonContactId(recordId);
Contact con = new Contact();
con.Id = accConId[0].personcontactId;
con.Profile_Photo__c = cdlink.ContentDownloadUrl;
update con;
return con.Profile_Photo__c;
}

Note : You can handle Apex class updates as per your requirement.

Croppie.js in action :

Conclusion :

By implementing this you can now crop the images using Salesforce and store them in salesforce using Croppie, we have multiple types of crop shapes are available. We can update these as per our requirements.

--

--