Get image from rich text field in Salesforce

by Rijwan Mohmmed
2 comments
get-image-from-rich-text-field-in-salesforce-techdicer

Hello Friends, Today, I will show you, how you can Get image from rich text field in Salesforce Apex that has been inserted in the rich text area on sobject. A sample code can be found in this unit that reads the image URL from the account object. Visualforce will display the image using this image URL. Let’s get started!

Also check this: Generate XML data in Apex

Key Highlight :

  1. Fetch only image URL from richtext
  2. Can show in LWC /LC or visualforce page

Code:

getImageCtrl.cls:

public class getImageCtrl {
    public string imageUrl{get;set;}
    
    public getImageCtrl(){
        List<Contact> con = [SELECT Id, Image__c FROM Contact WHERE Id ='0036F000034nono'];
        if(!con.isEmpty()){
            imageUrl = fetchImageUrl(con[0].Image__c);
        }
    }
    
    @AuraEnabled (cacheable=true)
    public getImageCtrlForLWC(){
        List<Contact> con = [SELECT Id, Image__c FROM Contact WHERE Id ='0036F000034nono'];
        if(!con.isEmpty()){
            imageUrl = fetchImageUrl(con[0].Image__c);
        }
    }
    
    public string fetchImageUrl(String imageRichText){
        Matcher imgMatcher = Pattern.compile( '<img(.+?)>' ).matcher(imageRichText);
        String img = '';
        while (imgMatcher.find()){                
            String imageTag = imgMatcher.group();
            img = imageTag.substringBetween(' src="', '"' );
            System.debug('img ===>' + img);
        }
        return img.unescapeHtml4();
    }
}

richtextimage.vf:

<apex:page controller="getImageCtrl">
  <!-- Begin Default Content REMOVE THIS -->
  <h1>This is your : richtextimage</h1><br/>
     <img src="{!imageUrl}"/>
</apex:page>

Output :

get-image-from-rich-text-field-in-salesforce-output-techdicer
get-image-from-rich-text-field-in-salesforce-output-techdicer

Reference :

  1. Salesforce Apex
What’s your Reaction?
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

2 comments

Manasa August 8, 2022 - 5:02 am

How to call this method from LWC ?Can you please update LWC code ?

Reply
Rijwan Mohmmed August 8, 2022 - 1:07 pm

Hi @Manasa, I have created a Auraenabled method in LWC, you just need to call this

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.