Click here to Skip to main content
Click here to Skip to main content
Go to top

Load Base64 Images using jQuery and MVC

, 26 May 2011
Rate this:
Please Sign up or sign in to vote.
This small article presents an example to load Base64 images using jQuery and MVC.

Introduction

This small article presents an example to load Base64 images using jQuery and MVC.

Background

It is not the most efficient way, but you may find that loading images in the "Base64" format can give you some conveniences in some cases. You can programmatically cache the images either in the memory or in the "local storage" at your browser and selectively display them without going to the server once the images are loaded. This article is to present an example to load Base64 images using "jQuery" and "MVC".

SolutionExplorer.jpg

The attached Visual Studio solution is developed in Visual Studio 2010. It has an MVC 2 web application "Base64Img". The version of the "jQuery" used here is "1.6.1".

  • The "Index.aspx" is the single view of this small application.
  • The "HomeController.cs" implements the controller that loads the "Index.aspx" page.
  • The "ImageController.cs" implements the controller that loads the image.
  • The "Tiger.jpg" is the image to be loaded in "Base64" format through the "ImageController" to the "Index.aspx" using "jQuery".

I will first introduce the controllers and then introduce the "Index.aspx" page to show you how the "Base64" image is loaded and displayed in the browser.

The MVC Controllers

The only functionality of the "HomeController" implemented in the "HomeController.cs" is to load the "Index.aspx" page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Base64Img.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
    }
}

The "ImageController.cs" implements the controller that loads the image and passes it in "Base64" format to the web browser.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
 
namespace Base64Img.Controllers
{
    public class ImageController : Controller
    {
        [HttpGet]
        public ActionResult GetBase64Image()
        {
            string path 
                = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images")
                 + "\\" + "Tiger.jpg";
 
            FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] data = new byte[(int)fileStream.Length];
            fileStream.Read(data, 0, data.Length);
 
            return Json(new { base64imgage =  Convert.ToBase64String(data) }
                , JsonRequestBehavior.AllowGet);
        } 
    }
}

The action method "GetBase64Image" takes no parameter, it reads the image file located in the "Images" folder and converts it to "Base64" format. It then sends the image to the browser as an "JsonResult".

The "Index.aspx" View

This MVC 2 application's single view page is implemented in the "Index.aspx" file.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Base64 Image Loader</title>
<link rel="stylesheet"
        href="<%: Url.Content("~/Content/Styles/Site.css") %>" />
<script
    src="<%: Url.Content("~/Content/Scripts/jquery-1.6.1.min.js") %>"
    type="text/javascript">
</script>
 
<script language="javascript" type="text/javascript">
    var imageUrl
        = "<%: Url.Action("GetBase64Image", "Image") %>";
    var imgs = null;
 
    $(document).ready(function () {
        if ($.browser.msie) {
            var browserMsg
                 = "Your browser does not support Base64 image"
            $("#divBrowserInfo").html(browserMsg);
 
            $("#btnClearImage").attr("disabled", true);
            $("#btnLoadImage").attr("disabled", true);
        }
 
        var displayImage = function (base64Data) {
            var imag = "<img "
                     + "src='" + "data:image/jpg;base64,"
                     + base64Data + "'/>";
 
            $("#divImageHolder").html(imag)
        };
 
        $("#btnLoadImage").click(function () {
            if (imgs != null) {
                displayImage(imgs.base64imgage);
                return;
            }
 
            $.ajax({
                cache: false,
                type: "GET",
                url: imageUrl,
                contentType: 'application/json',
                dataType: "json",
                success: function (data) {
                    imgs = data;
                    displayImage(imgs.base64imgage);
                },
                error: function (xhr) {
                    alert("Error occurred while loading the image. "
                        + xhr.responseText);
                }
            });
        });
 
        $("#btnClearImage").click(function () {
            $("#divImageHolder").html("");
        });
    });
</script>
</head>
 
<body>
    <div id="divBrowserInfo"></div>
    <div id="divImageHolder"></div>
    <div>
        <button id="btnClearImage">
            Clear Image</button>
        <button id="btnLoadImage">
            Load Base64 Image</button>
    </div>
</body>
</html>

The "Index.aspx" page has two button controls.

  • The click event on the "Load Base64 Image" button triggers the loading and displaying of the "Base64" image.
  • The click event on the "Clear Image" button clears the image from the web browser.

Before loading the image, the "JavaScript" code will first check if the image has been loaded. If the image has been loaded, it will simply display the loaded image. If the image is not loaded, it will initiate an "Ajax" call to the "ImageController" controller to load it. Since some versions of the "Internet Explorer" do not display "Base64" encoded image, if the user is using "Internet Explorer", I will display the "Your browser does not support Base64 image" message and disable the buttons.

Run the Application

Now we finish this small example, we can then run the application. The following shows the web application in "Safari".

RunAppStart.jpg

Click on the "Load Base64 Image" button, the "jQuery" "Ajax" call retrieves the image in "Base64" format from the "ImageController " and displays it in the browser.

RunAppPicLoad.jpg

If you click the "Clear Image" button to clear the image and click the "Load Base64 Image" again, you may notice that the tiger picture is shown to you must faster, because the "Base64" data is already loaded and the "JavaScript" code simply displays the cached image without initiating another "Ajax" call.

Points of Interest

  • This small article presented an example to load Base64 images using "jQuery" and "MVC".
  • This small example demonstrated the following techniques:
    • How to create an action method in the MVC controllers to send a "Json" object to the browser.
    • How to use a "jQuery" "Ajax" call to access an action method to load a "Json" object.
    • How to find the correct path of a file in the server and how to read the file.
    • How to convert some binary data to "Base64" format.
    • How to display images using "Base64" data using "jQuery".
    • How to identify the browser type using "jQuery".

I hope you like my postings and I hope that this article can help you in one way or the other.

History

This is the first revision of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dr. Song Li

United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberHoyaSaxa9327-May-11 3:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 26 May 2011
Article Copyright 2011 by Dr. Song Li
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid