<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" ref="style.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="script.js"></script>
    </head>
    <body>
        <table id="outputTable">
          <thead>
            <tr id="rowHeader">
              <th>Instructions<hr /></th>
            </tr>
          </thead>
          <tbody>
            <tr id="rowInstructions">
              <td>
                <ol>
                  <li>Enter the test image resource (url) in the script.js file (variable: "testUrl1").</li>
                  <li>Click the Demo button.</li>
                  <li>Result: 2 images will display:
                    <ul>
                      <li>Top: Image generated without including a canvas element in the function.</li>
                      <li>Bottom: Image generated by first creating a canvas element.</li>
                    </ul>
                  </li>
                </ol>
              </td>
            </tr>
            <tr id="rowButton">
              <td><hr />
                <input type="button" id="trigger" value="Click for Demo" />
              </td>
            </tr>
            <tr id="rowImagesHeader">
                <td>
                  <h2 id="outputHeader">Output</h2>
                  <hr />
                </td>
            </tr>
            <tr id="rowImage1">
              <td id="target">
                <h2>No Canvas</h2>
                <img id="image1" src="" />
              </td>
            </tr>
            <tr id="rowImage2">
              <td id="target2">
                <h2>Canvas</h2>
              </td>
            </tr>
            <tr id="rowData">
              <td id="dataCell">
                <h2>Data Output</h2>
                <hr />
                <div id="dataOutput"></div>
              </td>
            </tr>
          </tbody>
        </table>
    </body>
</html>
var $j = jQuery;

var testUrl1 = '';  //Enter image url resource here.

var imgSrc = testUrl1;

/* Base 64 Encoding Function */
function base64Encode(str) {
        var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var out = "", i = 0, len = str.length, c1, c2, c3;
        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                out += CHARS.charAt(c1 >> 2);
                out += CHARS.charAt((c1 & 0x3) << 4);
                out += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                out += CHARS.charAt(c1 >> 2);
                out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
                out += CHARS.charAt((c2 & 0xF) << 2);
                out += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            out += CHARS.charAt(c3 & 0x3F);
        }
        console.log(out);
        return out;
    }

/* Display and Encode without using "canvas" */
function displayNoCanvas( imgObj, data ){
  $j(imgObj).attr('src', 'data:image/jpeg;base64,' + base64Encode(data));
}

/* Display and Encode using "canvas" */
function displayWithCanvas ( targetDiv, data ){
  var img = new Image();
  img.onload = function(){
    var canvas1 = document.createElement("canvas");
    canvas1.width = this.width;
    canvas1.height = this.height;
    var ctx = canvas1.getContext('2d');
    ctx.drawImage(this, 0, 0);
    var dataUrl = canvas1.toDataURL({format: "png"});
  }
  img.src = 'data:image/jpeg;base64,' + base64Encode(data);
  $j(targetDiv).append(img);
}

/* Display base 64 encoded string */
function displayBase64Data( dataDiv, data ){
  var dataOut = base64Encode(data);
  $j( dataDiv ).append(dataOut);
}


// jQuery document ready function wrapper.
$j(document).ready(function(){
    var imgUrl = imgSrc;
    //var img = encodeURIComponent(imgUrl);
    $j('#trigger').click(function(){
        $.ajax({
            url: imgUrl,
            type: "GET",
            /*
            //Headers may need to be changed for compatibility with Safari
            beforeSend: function(xhr){
                xhr.setRequestHeader();
            }*/
            mimeType: "text/plain; charset=x-user-defined",
        }).done(function( data, textStatus, jqXHR ){
            //No Canvas
            displayNoCanvas( '#image1', data );
            //With Canvas
            displayWithCanvas( '#target2', data);
            //Show raw base64 data
            displayBase64Data( '#dataOutput', data);
        });
        
    });
    
});
/* Styles go here */
#outputTable {
  width: 100%;
}
#rowImage1 {
  width: 100%;
}
#rowImage2 {
  width: 100%;
}
#dataCell {
  max-width: 100%;
}
#dataOutput {
 width: 100%;
 word-wrap: break-word;
 overflow-wrap: break-word;
}
# Base64 Encode JPEG with AJAX #

---

## How to Use the Demo ##
1. Enter the test image resource (url) in the script.js file (variable: "testUrl1").
2. Click the Demo button.
3. Result: 2 images will display:
* Top: Image generated without including a canvas element in the function.
* Bottom: Image generated by first creating a canvas element.

## Functions ##
### Base64 Encoding Function ###
        /* Base 64 Encoding Function */
        function base64Encode(str) {
          var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
          var out = "", i = 0, len = str.length, c1, c2, c3;
          while (i < len) {
              c1 = str.charCodeAt(i++) & 0xff;
              if (i == len) {
                  out += CHARS.charAt(c1 >> 2);
                  out += CHARS.charAt((c1 & 0x3) << 4);
                  out += "==";
                  break;
              }
              c2 = str.charCodeAt(i++);
              if (i == len) {
                  out += CHARS.charAt(c1 >> 2);
                  out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
                  out += CHARS.charAt((c2 & 0xF) << 2);
                  out += "=";
                  break;
              }
              c3 = str.charCodeAt(i++);
              out += CHARS.charAt(c1 >> 2);
              out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
              out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
              out += CHARS.charAt(c3 & 0x3F);
          }
          console.log(out);
          return out;
      }
### Display Without Canvas ###
        /* Display and Encode without using "canvas" */
        function displayNoCanvas( imgObj, data ){
          $j(imgObj).attr('src', 'data:image/jpeg;base64,' + base64Encode(data));
        }
### Display With Canvas ###
        /* Display and Encode using "canvas" */
        function displayWithCanvas ( targetDiv, data ){
          var img = new Image();
          img.onload = function(){
            var canvas1 = document.createElement("canvas");
            canvas1.width = this.width;
            canvas1.height = this.height;
            var ctx = canvas1.getContext('2d');
            ctx.drawImage(this, 0, 0);
            var dataUrl = canvas1.toDataURL({format: "png"});
          }
          img.src = 'data:image/jpeg;base64,' + base64Encode(data);
          $j(targetDiv).append(img);
        }
### Display Encoded String ###
        /* Display base 64 encoded string */
        function displayBase64Data( dataDiv, data ){
          var dataOut = base64Encode(data);
          $j( dataDiv ).append(dataOut);
        }
### AJAX: Execute Demo ###
        // jQuery document ready function wrapper.
        $j(document).ready(function(){
          var imgUrl = imgSrc;
          $j('#trigger').click(function(){
            $.ajax({
              url: imgUrl,
              type: "GET",
              /*
              //Headers may need to be changed for compatibility with Safari
              beforeSend: function(xhr){
                xhr.setRequestHeader();
              }*/
              mimeType: "text/plain; charset=x-user-defined",
            }).done(function( data, textStatus, jqXHR ){
              //No Canvas
              displayNoCanvas( '#image1', data );
              //With Canvas
              displayWithCanvas( '#target2', data);
              //Show raw base64 data
              displayBase64Data( '#dataOutput', data);
            });
          });
        });