Foliotek Developer Blog

Copy Images from Clipboard in Javascript

One of the pretty common in a Windows environment is copy/pasting image data across programs. In recent versions of chrome, this is now possible in the browser. Here is a quick demo of the javascript we’ll be starting from — you can copy image data from anywhere (Paint, Word, Screenshot, etc) and paste it into the div to have it appended.

http://jsfiddle.net/FhUwn/

This just appends an image that looks something like:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIkAAAAqCAYAAACHr...C">  

Which is pretty powerful in it’s own right, but it’s not terribly well supported across browsers – for Foliotek Presentation, ideally we would create a file they can manage just like any of their other files from the paste data, so, with a quick change to the reader.onload, we’ll upload the image to the server:

reader.onload = function(evt) {  
    var result = evt.target.result; 
    var arr = result.split(","); 
    var data = arr[1]; // raw base64 
    var contentType = arr[0].split(";")[0].split(":")[1]; // image/png, image/gif, etc 
    $.post("imageupload", {
        data: data, contenttype: contentType,
    }, function (ev) {
        var img = $("<img style='display:none;' src='" + ev.URL + "' />");
        img[0].onload = function () {
            var width = img.width();
            var height = img.height();
            var src = "<img src='" + ev.URL + "' width='" + width + "' height='" + height + "' />";
            div.append($(src)); img.remove();
        };
        $("body").append(img);
    });
};

And the content of the “imageupload” server route is pretty straightforward, and not too different than what you’d have for uploading an image from Post data:

 public JsonResult imageupload(string data, string contenttype) {
    byte[] bytes = Convert.FromBase64String(data);
    var ms = new MemoryStream(bytes, 0, bytes.Length);
    UserFile file = SaveByteArrayAsUserFile(User, bytes, contentType); // saves the content as a file associated with that user 

    return Json(new {
        file.Name,
        file.URL
    });
}

Pretty powerful, and definitely one further step in making web-apps feel like native OS apps.