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 :
- Fetch only image URL from richtext
- 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 :
Reference :
What’s your Reaction?
+1
1
+1
+1
+1
+1
+1
2 comments
How to call this method from LWC ?Can you please update LWC code ?
Hi @Manasa, I have created a Auraenabled method in LWC, you just need to call this