Click here to Skip to main content
15,867,330 members
Articles / Programming Languages / Javascript

Load Base64 Images using jQuery and MVC

Rate me:
Please Sign up or sign in to vote.
4.92/5 (9 votes)
26 May 2011CPOL3 min read 128.4K   2.2K   25   8
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.

C#
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.

C#
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.

ASP.NET
<%@ 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)


Written By
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

 
QuestionThanks Pin
Anoop PV23-Jul-14 21:45
Anoop PV23-Jul-14 21:45 
AnswerRe: Thanks Pin
Dr. Song Li24-Jul-14 3:31
Dr. Song Li24-Jul-14 3:31 
GeneralMy vote of 5 Pin
alon23-Mar-14 12:56
alon23-Mar-14 12:56 
QuestionGreat article! (one small remark) Pin
E.F. Nijboer28-Feb-13 1:41
E.F. Nijboer28-Feb-13 1:41 
AnswerRe: Great article! (one small remark) Pin
Dr. Song Li28-Feb-13 3:51
Dr. Song Li28-Feb-13 3:51 
GeneralMy vote of 5 Pin
honorioyango27-Sep-12 19:32
honorioyango27-Sep-12 19:32 
QuestionHow to upload the image Pin
honorioyango27-Sep-12 19:29
honorioyango27-Sep-12 19:29 
GeneralMy vote of 5 Pin
HoyaSaxa9327-May-11 3:34
HoyaSaxa9327-May-11 3:34 

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

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