Skip to content

Instantly share code, notes, and snippets.

@sectore
Created December 22, 2011 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sectore/1511618 to your computer and use it in GitHub Desktop.
Save sectore/1511618 to your computer and use it in GitHub Desktop.
Client-side Roundtrip to send and receive (binary) image data using Socket.IO
###
1 SENDING DATA
1.1 get original image data clicking on it
1.2 get its base64-encoded data
1.3 emit the data by Socket.IO to server (Node.js)
###
$(".my-image").click (event) =>
# get image which was clicked
img = event.target
# create base64 encoded image
imgdata = @getBase64Image(img)
# emit data to clients
@socket.emit 'onimgdata', { width: img.width, height: img.height, source:imgdata }
###
Helper method to get a base64 encoded image data
Based on http://stackoverflow.com/questions/934012/get-image-data-in-javascript
###
getBase64Image:(img) ->
# create canvas
canvas = document.createElement "canvas"
canvas.width = img.width
canvas.height = img.height
context = canvas.getContext "2d"
# draw image into canvas
context.drawImage img,
0,
0
###
Get the data-URL formatted image
using jpeg format as the type of the image to be returned
@see: http://www.w3.org/TR/html5/the-canvas-element.html
###
data = canvas.toDataURL "image/jpeg"
#return data
data
###
2 RECEIVING DATA + DISPLAY IMAGE
2.1 listen to "showimgdata" event sent from server (Node.js)
2.2 push data to HTML image
###
@socket.on 'showimgdata', (data) ->
#get image
img = $('#show-img').get 0
message
try
# set data for image
img.width = data.width;
img.height = data.height;
img.src = data.source;
message = ''
catch error
console.log error
message = 'error receiving image data...'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment