Articles in this section
Category / Section

Compressing Base64 Images for React RichTextEditor

3 mins read

When working with images in the React RichTextEditor, it may be necessary to compress Base64 images before inserting them. This can help improve performance and reduce the size of the data being handled. Below is a guide on how to achieve this using the actionBegin and actionComplete events.

Initialize the Rich Text Editor

Initialize the Rich Text Editor component by configuring the required toolbarSettings and binding the actionBegin and actionComplete events to handle custom logic during editor operations. Additionally, configure the insertImageSettings to define the format for storing images in the Rich Text Editor.


<RichTextEditorComponent id="defaultRTE" actionBegin={actionBegin}
           actionComplete={actionComplete} insertImageSettings={insertimageSettings}
           ref={(richtexteditor) => {rteObj = richtexteditor;}} >
    <Inject  services={[HtmlEditor, Toolbar, Image, Link, QuickToolbar,                              Table, Video, Audio, PasteCleanup,]}/>
</RichTextEditorComponent>

Implementation Steps

  1. Set Insert Image Settings: Configure the settings for inserting images.
  const insertimageSettings = {
    saveFormat: 'Base64',
  };
  1. Define the actionBegin Function: This function will handle the image compression when an image is being inserted.
  let modifiedUrl;
  async function actionBegin(args) {
    if (args.requestType == 'Image') {
      const originalBase64 = args.itemCollection.url;
      modifiedUrl = await compressBase64ImageAlt(originalBase64, 600, 0.7);

      args.itemCollection.url = modifiedUrl;
      const base64Body = args.itemCollection.url.split(',')[1];

      // Decode the base64 string to get the binary data
      const binaryString = atob(base64Body);
      console.log(binaryString.length);
    }
  }
  1. Create the Compression Function: This function will handle the actual compression of the Base64 image.

    async function compressBase64ImageAlt(base64, maxWidth = 800, quality = 0.7) {
      // Convert base64 to Blob
      const response = await fetch(base64);
      const blob = await response.blob();
    
      // Create image bitmap for performance
      const bitmap = await createImageBitmap(blob);
    
      const scaleFactor = maxWidth / bitmap.width;
      const newWidth = maxWidth;
      const newHeight = bitmap.height * scaleFactor;
    
      // Create OffscreenCanvas
      const canvas = new OffscreenCanvas(newWidth, newHeight);
      const ctx = canvas.getContext('2d');
    
      ctx.drawImage(bitmap, 0, 0, newWidth, newHeight);
    
      // Convert canvas to Blob (JPEG with compression)
      const compressedBlob = await canvas.convertToBlob({
        type: 'image/jpeg',
        quality: quality,
      });
    
      // Convert Blob to Base64
      const reader = new FileReader();
      return new Promise((resolve) => {
        reader.onloadend = () => {
          resolve(reader.result);
        };
        reader.readAsDataURL(compressedBlob);
      });
    }
    
  2. Define the actionComplete Function: This function will finalize the image insertion after compression.

    async function actionComplete(args) {
      if (args.requestType == 'Images') {
        setTimeout(() => {
          args.elements[0].src = modifiedUrl;
        }, '1000');
      }
    }
    

Conclusion

I hope you enjoyed learning how to compress Base64 Images for the React RichTextEditor.

You can refer to the React RichTextEditor feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React RichTextEditor example to understand how to create and manipulate data.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied