How to Render Blob on visualforce Page?

I have Base 64-encoded binary data and I want to render that as an image on a Visualforce Page. Is that possible? How can it be done?

Answer

This is a really interesting question which showcases some powerful (though not necessarily recommended) platform capabilities. To answer it:

BlobController.cls

public class BlobController {
  public String getData() {
    return
      'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAzklEQVQ4y2P4//8/AyWYgWoGwMEFBi0g' +
      'XgLEb4H4FxD/BuLXQNwHxPwwZdgNuMDgDcS3GR4w7Gf4yfCE4T8UgtggsQsMH4DYHrsBFxiUgfgVw1eG' +
      'm3CN6BAkd4HhGhArYTNgDtiW/wQgxCVTsBnwCcXZuCBIzQWGB9gM+EdQMwxeYPiGzYD/JBjwFZsBz0jw' +
      'wh1sBswiIRAbsBkgDsTviIjGpyC1uBKSJRBfx5OQLgOxLu6UCDFEEYh7oQnmCyjEgfgeELcAsSzOpDxg' +
      'uREA1co5dU5YrgAAAAAASUVORK5CYII='
    ;
  }
}

Blob.page

<apex:page controller="BlobController">
    <apex:image value="data:image;base64,{!Data}" />
</apex:page>

Base64 data to image

Genericizing this with a component:

Potentially, this could be used (eg) to minimize HTTP requests in overhead-critical applications such as mobile clients. Without the need for a build process. This use of PageReference.getContent may be contentious, and you’d need to consume SOQL queries to properly surface the MIME types, but this works for example’s sake:

DataUriForResourceController.cls

public class DataUriForResourceController {
  public String path {
    get; set;
  }

  public String getData() {
    return EncodingUtil.base64encode(new PageReference(this.path).getContent());
  }
}

dataUriForResource.component

<apex:component layout="none" selfClosing="true" controller="DataUriForResourceController"><!--
--><apex:attribute required="true" name="path" type="String" description="Path for the static resource whose content will be fetched, eg '/resource/myResourceNameZip/file.ext'" assignTo="{!path}" /><!--
-->data:image;base64,<apex:outputText value="{!Data}" escape="false" /><!--
--></apex:component>

Usage:

JustInTimeCss.page

<apex:page contentType="text/css" cache="true" expires="300">
  div.panel {
    border:1px solid #CCC;
    background-image: url('<c:dataUriForResource path="{!URLFOR($Resource.myPng)}" />');
    padding:10px;
    margin:10px;
  }
</apex:page>

Attribution
Source : Link , Question Author : Axaykumar Varu , Answer Author : Matt and Neil

Leave a Comment