Image compression within a Lightning Web Component (LWC) or any web application is a technique used to optimize and enhance the performance and user experience. In this blog post, we’ll explore the importance of image compression, the steps involved in implementing it in a Lightning Web component, and the benefits it offers.
Benefits of Image Compression:
Before diving into the implementation details, let’s first understand why image compression is crucial in web applications:
Faster Page Loading: Large, uncompressed images can significantly slow down page loading times. Compressed images reduce data transfer, resulting in faster loading and a smoother user experience.
Improved User Experience: Users expect web applications to be fast and responsive. Image compression helps achieve this by reducing image loading times.
Reduced Storage Costs: Storing large images can be costly, especially in cloud-based applications. Image compression lowers storage requirements, saving both space and expenses.
Search Engine Optimization (SEO): Search engines consider page loading times as a ranking factor. Faster-loading pages improve your website’s visibility and SEO rankings.
Optimized Mobile Experience: Many users access web applications on mobile devices. Image compression ensures that your app loads quickly and efficiently on various screen sizes.
Implementation Steps
Now, let’s explore the implementation of image compression within a Lightning Web component:
HTML Template
In the HTML template, we set up the file input element using the lightning-input component. This input element allows users to select an image file for compression. The onchange event handler is used to trigger the image compression process when a file is selected.
<template>
<lightning-input label=”Upload Image”
type=”file”
accept=”image/*”
name=”file1″
onchange={handleFileChange}>
</lightning-input>
JavaScript (JS) Code
The JavaScript code handles the image compression process. It begins with importing the necessary Lightning Web components and Lightning Platform features.
handleFileChange Function
The handleFileChange function is called when a file is selected. It manages the following:
- Extracts the selected image’s name and type.
- Reads the file content.
- Creates an Image object to load and analyze the uploaded image.
- Determines the maximum dimensions for the compressed image.
- Creates a canvas element and resizes the image, drawing it onto the canvas.
- Uses the toDataURL method to convert the canvas content to a base64 data URL with the specified file type and quality (0.7).
- Stores the compressed image data in the compressedImageData attribute.
Creating a ContentVersion Record
The code prepares the necessary fields to create a ContentVersion record in Salesforce, including the compressed image data. It utilizes the createRecord function to create the record.
Error Handling and Success Toast Message
Error handling is implemented in the code, including the display of error toast messages using the showErrorToast function.
A success toast message is also displayed using the showSuccessToast function when the file upload is successful.
Full JS Code:
import { LightningElement, api, track, wire } from ‘lwc’;
import { ShowToastEvent } from ‘lightning/platformShowToastEvent’;
import { createRecord } from ‘lightning/uiRecordApi’;
import { NavigationMixin } from ‘lightning/navigation’;
export default class cameraCapture extends NavigationMixin(LightningElement) {
@api recordId;
@track compressedImageData = ”;
@track fileName = ”;
@track fileType = ”;
@track newfile = false;
handleFileChange(event) {
console.log(‘apple’);
const fileInput = event.target.files;
const file = fileInput[0];
this.fileName = file.name;
this.fileType = file.type;
const reader = new FileReader();
reader.onload = () => {
const readerResult = reader.result;
var image = new Image();
image.src = readerResult;
image.onload = () => {
const maxWidth = 2800;
const maxHeight = 2600;
var canvas = document.createElement(‘canvas’);
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
var context = canvas.getContext(‘2d’);
context.drawImage(image, 0, 0, width, height);
const compressedImageData = canvas.toDataURL(this.fileType, 0.7);
this.compressedImageData = compressedImageData;
const fields = {
Title: this.fileName,
PathOnClient: this.fileName,
VersionData: this.compressedImageData.split(‘,’)[1],
FirstPublishLocationId: this.recordId,
ContentLocation: ‘S’,
Description: this.description
// Add any other fields you need
};
createRecord({
apiName: ‘ContentVersion’,
fields: fields
})
.then(result => {
this.showSuccessToast(‘Success!’, ‘File has been uploaded successfully.’);
this.newfile = true;
})
.catch(error => {
console.error(‘Error in callback:’, error);
this.showErrorToast(‘Error’, ‘An error occurred while uploading the file.’);
});
};
};
reader.readAsDataURL(file);
}
showErrorToast(title, message) {
const evt = new ShowToastEvent({
title: title,
message: message,
variant: ‘error’
});
this.dispatchEvent(evt);
}
showSuccessToast(title, message) {
const evt = new ShowToastEvent({
title: title,
message: message,
variant: ‘success’
});
this.dispatchEvent(evt);
}
}
Conclusion:
In conclusion, image compression in a Lightning Web component, as in any web application, is a performance and user experience optimization technique. It leads to faster loading times, reduced data usage, cost savings, and a better user experience. Additionally, it contributes to environmental sustainability by reducing data transfer and energy consumption.
Incorporating image compression into your web application can have a significant impact on its performance and user satisfaction. By following the steps outlined in this blog post, you can enhance the efficiency of your Lightning Web component and provide a seamless experience for your users.
Related blogs: