gregs

Embedded image

by gregs on Mar.13, 2007, under ColdFusion

A client recently decided to start storing all of their images in a database and usually we would point the image source to a cfm page, where we'd do something like this:

CODE:
  1. request.uploadedPic = application.staffManager.getStaffImage(session.user.getId());
  2. context = getPageContext();
  3. context.setFlushOutput(false);
  4. response = context.getResponse().getResponse();
  5. out = response.getOutputStream();
  6. response.setContentType("image/jpeg");
  7. response.setContentLength(arrayLen(request.uploadedPic['staffPhoto'][1]));
  8. out.write(request.uploadedPic['staffPhoto'][1]);
  9. out.flush();
  10. response.reset();
  11. out.close();

Which worked nicely until I read about some performance issues with http calls and the cfdocument tag. Zac (yes his name pops up a lot in this blog), put me onto directly embedding the image into the source, like such:

CODE:
  1. <img src="data:image/jpeg;base64,&lt;cfoutput&gt;#BinaryEncode(request.uploadedPic['staffPhoto'][1],'Base64')#&lt;/cfoutput&gt;" alt="Embedded Image" />

No need to make a http call to display the image anymore.


3 Comments for this entry

  • Ben Nadel

    Does that embedded data thing work on all the modern browsers? That is totally awesome.

    Also, all that stuff you are doing in the first example was all required pre MX7 (getting the underlying byte stream and all). If you are on MX7, you can use the CFContent / variable attribute to stream binary data to the client:

  • Ryan

    I thought this method only worked in FireFox?

    You should embed a test image in this post, then we can all try it out.

  • gregs

    It works for both FireFox and Safari. Just had a quick go using IE7 and sadly this trick doesn’t work.

1 Trackback or Pingback for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!