Created
May 17, 2011 02:15
-
-
Save hakobera/975762 to your computer and use it in GitHub Desktop.
WebSocket(Socket.IO) で受け取った Data URL 形式の画像をダウンロードさせる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'), | |
io = require('socket.io'), | |
fs = require('fs'); | |
var app = module.exports = express.createServer(); | |
// Configuration | |
app.configure(function(){ | |
app.set('views', __dirname + '/views'); | |
app.set('view engine', 'ejs'); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
app.use(express.static(__dirname + '/public')); | |
}); | |
app.configure('development', function(){ | |
app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); | |
}); | |
app.configure('production', function(){ | |
app.use(express.errorHandler()); | |
}); | |
// Routes | |
app.get('/', function(req, res){ | |
res.render('index', { | |
title: 'Express' | |
}); | |
}); | |
// Only listen on $ node app.js | |
if (!module.parent) { | |
app.listen(3000); | |
console.log("Express server listening on port %d", app.address().port); | |
var socket = io.listen(app); | |
socket.on('connection', function(client) { | |
client.on('message', function(message) { | |
fs.readFile('./images/test.jpg', function (err, data) { | |
if (err) { | |
throw err; | |
} | |
var prefix = 'data:image/jpeg;base64,', | |
base64 = new Buffer(data, 'binary').toString('base64'), | |
data = prefix + base64; | |
client.send(data); | |
}); | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener('DOMContentLoaded', function() { | |
var screen, screenContext, socket, downloadLink; | |
screen = document.createElement('canvas'); | |
screen.width = 1600; | |
screen.height = 1200; | |
screenContext = screen.getContext('2d'); | |
socket = new io.Socket('localhost'); | |
socket.connect(); | |
downloadLink = document.getElementById('download'); | |
// data は base64 でエンコードされた JPEG 画像データ | |
socket.on('message', function(data) { | |
var img = new Image(); | |
img.onload = function() { | |
// 縮小して、PNGに変換 | |
screenContext.drawImage(img, 0, 0, 800, 600); | |
img = null; | |
downloadLink.href = screen.toDataURL('image/png'); | |
}; | |
img.src = data; | |
}); | |
// サーバーから画像取得 | |
socket.send('get test.jpg'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment