[SalesForce] Displaying Images on Visualforce pages using Base64 Blob

My question is about displaying base64 blob as image in visualforce page. Here's my controller code:

Object img;
public Object getImg () {
    List<ContentVersion> bodyList = [SELECT VersionData FROM ContentVersion WHERE ContentDocumentId='the real id'];

    img = bodyList[0].get('VersionData');
    return img;
}

Here's the visualforce:

<img src="data:image/png;base64,{! img }"/>

This is getting rendered as

<img src="data:image/png;base64,core.filemanager.FileBlobValue@1e76577f">

How can I get the actual base64 of image so the image is displayed properly?

Best Answer

Figured it out after debugging a bit more.

Blob img;
public Object getImg () {
    List<ContentVersion> bodyList = [SELECT VersionData FROM ContentVersion WHERE ContentDocumentId='insert your id'];

    img = (Blob) bodyList[0].get('VersionData');
    return EncodingUtil.base64Encode(img);
}

All I had to do was to typecast the Object as Blob and then encode the blob value.

Related Topic