• WHO WE ARE
  • WHAT WE DO
    • Salesforce
      • Implementations
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service Lightning
        • Field Service for SMEs
      • Developments
        • Salesforce Customization
        • Custom Application Development
        • AppExchange Product Development
      • Migrations
        • Classic to Lightning Migration
        • Other Systems to Salesforce Migration
      • Integrations
    • Data Science
      • BI Solutions
      • AI/ML solutions
      • Agentic AI
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG
    • WHO WE ARE
    • WHAT WE DO
      • Salesforce
        • Implementations
          • Sales Cloud
          • Service Cloud
          • CPQ
          • Field Service Lightning
          • Field Service for SMEs
        • Developments
          • Salesforce Customization
          • Custom Application Development
          • AppExchange Product Development
        • Migrations
          • Classic to Lightning Migration
          • Other Systems to Salesforce Migration
        • Integrations
      • Data Science
        • BI Solutions
        • AI/ML solutions
        • Agentic AI
    • HOW WE DO
      • Delivery Model
      • Our Works
    • REACH US
      • Contact Us
      • Careers
    • BLOG
  • [email protected]
  • (+91) 44-49521562
Merfantz - Salesforce Solutions for SMEs
Merfantz - Salesforce Solutions for SMEs
  • WHO WE ARE
  • WHAT WE DO
    • Salesforce
      • Implementations
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service Lightning
        • Field Service for SMEs
      • Developments
        • Salesforce Customization
        • Custom Application Development
        • AppExchange Product Development
      • Migrations
        • Classic to Lightning Migration
        • Other Systems to Salesforce Migration
      • Integrations
    • Data Science
      • BI Solutions
      • AI/ML solutions
      • Agentic AI
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG

IMAGE COMPRESSION USING LIGHTNING WEB COMPONENT

  • November 3, 2023
  • Tech Blogger
  • Salesforce Development & Implementation, Salesforce Developments Tutorial, Salesforce Lightning
  • 0

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>

</template>
HTML Template Output

 

 

 

 

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:

How to change the text color in Salesforce lightning

Author Bio

Tech Blogger
+ Recent Posts
  • Let Einstein Help You Build - Salesforce Flow
    May 15, 2025
    Let Einstein Help You Build - Salesforce Flow
  • May 9, 2025
    Mastering Attachment Compression for Salesforce Developers
  • May 2, 2025
    Salesforce API Integrations: Connect with Slack, Zoom, and Teams
  • Guide to Streamlining Sales Success
    April 17, 2025
    Mastering Salesforce CPQ: A Comprehensive Guide to Streamlining Sales Success
Tags: Customized Salesforce ImplementationSalesforce Development & Implementation
  • Previous How to Create Daylight Saving Time (DST) using the formula.
  • Next How To Call Lightning Web Component From Visualforce Page
Merfantz Technologies is a leading Salesforce consulting firm dedicated to helping small and medium enterprises transform their operations and achieve their goals through the use of the Salesforce platform. Contact us today to learn more about our services and how we can help your business thrive.

Discover More

Terms and Conditions
Privacy Policy
Cancellation & Refund Policy

Contact Info

  • No 96, 2nd Floor, Greeta Tech Park, VSI Industrial Estate, Perungudi, Chennai 600 096, Tamil Nadu, INDIA
  • (+91) 44-49521562
  • [email protected]
  • 9:30 IST - 18:30 IST

Latest Posts

Let Einstein Help You Build - Salesforce Flow
Let Einstein Help You Build – Salesforce Flow May 15, 2025
Mastering Attachment Compression for Salesforce Developers May 9, 2025
Salesforce API Integrations: Connect with Slack, Zoom, and Teams May 2, 2025

Copyright @2023 Merfantz Technologies, All rights reserved