Image to Base64 Converter using SAP UI5

by | Feb 13, 2023 | UI5 Integrations

Home » SAP » UI5 » UI5 Integrations » Image to Base64 Converter using SAP UI5

Preface – This post is part of the UI5 Integration Programs series.

When do we need to convert an Image to Base64

You may want to convert an image to Base64 format for various reasons, some common use cases are:

  1. Storing images in databases: Instead of storing images as physical files, converting them to Base64 and storing the string in the database can simplify database management.
  2. Sending images in APIs: When sending images in APIs or other network protocols, it is often necessary to encode them as text-based data such as Base64, so they can be transmitted in a plain text format.
  3. Embedding images in HTML, CSS, or JavaScript: You can embed Base64 encoded images directly in your HTML, CSS, or JavaScript code, reducing the number of HTTP requests required to load a page.
  4. Reducing image file sizes: Base64 encoding increases the size of an image file, but it can be a useful optimization when multiple images are embedded in a single document, as it reduces the number of files that need to be loaded.

It is worth noting that Base64 encoding increases the size of an image file by about 33%, so it’s not the most efficient way to store large images. However, for smaller images and icons, the overhead is usually not a problem.

Steps to convert an Image to Base64 using JavaScript

Here are the steps to convert an image to Base64 using JavaScript:

1. Read the image file as a binary string using the FileReader API:

const reader = new FileReader();
reader.readAsDataURL(file);
2. Once the file has been read, the load event will be triggered, and the result will be available in the reader.result property. This result will be a data URL that represents the image in Base64 format:
reader.addEventListener("load", function() {
  const base64 = reader.result;
});

3. You can use the base64 variable in your JavaScript code to access the image data. For example, you can create an HTML img element and set its src attribute to the Base64 encoded image data:

const image = new Image();
image.src = base64;

Here’s a complete example that reads an image file and displays it on a page:

const input = document.querySelector("input[type='file']");
const imageContainer = document.querySelector("#image-container");
input.addEventListener("change", function(event) {
  const file = event.target.files[0];
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.addEventListener("load", function() {
    const base64 = reader.result;
    const image = new Image();
    image.src = base64;
    imageContainer.appendChild(image);
  });
});

 

Steps to convert an Image to Base64 using SAP UI5

In SAP UI5, you can use FileReader() function to convert the same. Codes are mentioned below:

View.xml

<mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
    xmlns:html="http://www.w3.org/1999/xhtml" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form" xmlns:RichTextEditor="sap.ui.richtexteditor">
    <Shell id="shell">
        <App id="app">
            <pages>
                <Page id="page" title="Image to Base64 Converter using UI5">
                    <content>
                        <VBox class="sapUiSmallMarginBegin">
                            <HBox>
                                <UploadCollection id="idDP" noDataText="Upload a square image preferably 640X640"
                                    maximumFilenameLength="30" maximumFileSize="1" multiple="false"
                                    sameFilenameAllowed="false" instantUpload="false" change="onChangeDP" fileDeleted="onFileDeletedDP" fileType="png,jpg,jpeg"
                                    filenameLengthExceed="onFilenameLengthExceed" fileSizeExceed="on1MBFileSizeExceed" typeMissmatch="onTypeMissmatch"
                                    uploadComplete="onUploadDPComplete" beforeUploadStarts="onBeforeUploadStarts"/>
                                <TextArea id="idBase64Area" value='Base 64 Value' editable="false" height="300px" width="500px"/>
                            </HBox>
                        </VBox>
                    </content>
                </Page>
            </pages>
        </App>
    </Shell>
</mvc:View>

 

Controller.js

sap.ui.define([
    "sap/ui/core/mvc/Controller"
], function (Controller) {
    "use strict";
    return Controller.extend("Test.Test.controller.Main", {
        onChangeDP: function (oEvent) {
            // Get File
            var that = this;
            var image = new Image();
            var file = oEvent.getParameter("files")[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                var data = reader.result;
                //Set the Base64 string return from FileReader as text area value.
                that.byId("idBase64Area").setValue(data);
                image.onload = function () {
                    //	Check if image is bad/invalid
                    if (this.width + this.height === 0) {
                        that.dpImage = "";
                        sap.m.MessageBox.error("Invalid Image!");
                    }
                };
            };
            reader.onerror = function (error) {
                //Error Handling
            };
        }
    });
});

Output

Image to Base64 Converter using UI5

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author