Working with Images: Javascript

In this post we will look at working with images in a demo Kii Cloud application. The example shows how to store, retrieve and delete image data using Kii’s Javascript API. Similar approaches can be taken with other Kii APIs, but we’ll use JS for an example.

Image files (binary data) can be represented as an object. In terms of Kii’s API we will need to create a Kii Object, with one of the fields (key-value pairs) containing the binary image data. Please note, that the maximum size allowed for an object is 65534 bytes, which means that if you need to load bigger images, you will need to resize them in advance.

First, let’s read an image from a file into a variable (blob):
HTML: create an input tag to select an image file and img tag to preview the image

<input type='file' id=" inputImage" />

<img id="img" src="" />

Javascript (using JQuery): as soon as an image file is selected, it will be set to preview and stored into the imageData variable.

var imageData;

function readImage(input) {

  if (input.files && input.files[0]) {

    var FR = new FileReader();

    FR.onload = function (e) {

      $('#img').attr("src", e.target.result);

      imageData = e.target.result;

      addToList(imageData, $('#inputImage').val());

    };

    FR.readAsDataURL(input.files[0]);

  }
}

$("#inputImage").change(function () {

  readImage(this);

});

After executing the code above, your user will see the image preview as shown below:

preview

Now that we have our image saved in a variable, we can store it in Kii cloud:

// get the defined bucket belonging to this user

var bucket = KiiUser.getCurrentUser().bucketWithName("myObjects");

// create the object

var object = bucket.createObject();

// set a key/value pair for image blob and image namr

object.set("myObjectValue", imageData);

object.set("myObjectName", fileUri);

// save the object

object.save( ....//insert necessary callbacks here...);

}

The code snippet above saves image data in the current user’s bucket in Kii cloud. If the save was successful, we can retrieve the image along with the other images already in the bucket:

// get the defined bucket belonging to this user

var bucket = KiiUser.getCurrentUser().bucketWithName("myObjects");

// create an empty KiiQuery (will return all objects in the bucket)

var queryObject = KiiQuery.queryWithClause(null);

// sort the results by creation date

queryObject.sortByAsc("_created");

// perform the asynchronous query, with callbacks defined

bucket.executeQuery(queryObject, {

  // callback for a successful query

  success: function (queryPerformed, resultSet) {

    //display the results

  },

  // callback for a failed query

  failure: function (queryPerformed, anErrorString) {

    // add some error handling
  }});

}

The code snippet above loads the whole set of objects in the bucket. However, if you only want to retrieve a particular image, you can do so using its “myObjectName” key:

var clause = KiiClause.equals("myObjectName", fileName);

var query = KiiQuery.queryWithClause(clause);

// Define the callbacks

var queryCallbacks = {

  success: function(queryPerformed, resultSet) {

    // display the results
  },

  failure: function(queryPerformed, anErrorString) {

     // do something with the error response

  }}

// Execute the query

bucket.executeQuery(query, queryCallbacks);

Once the image objects are retrieved from Kii Cloud, we just need to display them. The retrieved resultSet should be assigned to the global results variable for the future reference. The results will be displayed in the listview element on the page:

results = resultSet;

// clear the existing objects from the list

$("#listview").empty();

// iterate through the result set

for (var i = 0; i < resultSet.length; i++) {

  // create a row UI element based on the object

  var obj = resultSet[i];

  var row = createListItem(obj, i);

  // add the row to the list

  $("#listview").append(row);

}

// refresh the list to show the added results

$("#listview").listview('refresh');

The function below shows how a DOM element is created from Kii image object:

function createListItem(obj, index) {

  // set the KiiObject URI to an attribute so it can be tracked

  var row = $("<li></li>").attr("uri", index);

  var imgrow = $("<img></img>").attr("src", obj.get("myObjectValue"));

  $(row).append(imgrow);

  var deleteLink = $("<a></a>").attr("href", "javascript:removeFromList('" + index + "')");

  $(deleteLink).append("<p>delete " + obj.get("myObjectName") + "</p>");

  // append the delete button to the row

  $(row).append(deleteLink);

  // return the entire row

  return row;

}

The result will present a list of images from Kii cloud with delete links next to them:

list

Image deletion works exactly the same as deletion of any other Kii object. Since we already have the list of all objects, we can just remove them using their index in the list:

// called from the UI, this method removes an object from the server

function removeFromList(index) {

  // get a reference to the selected object

  var obj = results[index];

  // perform an asynchronous deletion, with callbacks

  obj.delete({

    // callback for a successful deletion

     success: function(theDeletedObject) {

      // find the associated UI element and remove it from the list

      $("[uri='"+index+"']").remove();

    },

    // callback for a failed deletion

    failure: function(theObject, anErrorString) {

      // do something about the error

    }

  });
}

That’s all! Happy coding 🙂 Full source is available for download here.

Kii Cloud is a full-stack mobile backend to accelerate iOS, Android, HTML5 and Unity app development. Optional ad network integration is available to help you monetize. Get started with a free account at developer.kii.com

- Share -

Tetyana Loskutova

More posts from

  • Kii IoT platform enables customers to create smart, connected solutions and services
  • Long track record of supporting customers like Docomo, Toshiba, Kyocera and many others
  • Strong ecosystem partners across the globe, consisting of carriers, device/sensor manufacturers, system integrators, network/infrastructure providers, chip vendors and solution developers
  • HQ in Tokyo, US HQ in Silicon Valley & offices in China, Taiwan, Hong Kong and Europe (UK, Spain, Germany)
  • www.kii.com