Created
March 7, 2012 16:30
-
-
Save leemartin/1994209 to your computer and use it in GitHub Desktop.
Waveform ImageData Node
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
app.get '/waveform', (req, res) -> | |
# If URL and Callback present | |
if req.param("url") && req.param("callback") | |
# Get the parameters | |
url = decodeURIComponent(req.param("url")) | |
callback = req.param("callback") | |
# Create a Bufferlist | |
bl = new BufferList() | |
# Request image and pass response to Bufferlist | |
request { uri: url, responseBodyStream: bl, encoding: null }, (error, response, body) -> | |
# console.log response.headers['content-type'] | |
# If the request was OK | |
if !error && response.statusCode == 200 | |
# Get MimeType | |
mimetype = response.headers["content-type"] | |
# Make sure it's a PNG | |
if mimetype == "image/png" | |
# Create the prefix for the data URL | |
type_prefix = "data:" + mimetype + ";base64," | |
# Get the image from the response stream as a string and convert it to base64 | |
# image = new Buffer(bl.toString(), 'binary') | |
image = new Buffer(body) | |
image_64 = body.toString('base64') | |
# Concat the prefix and the image | |
image_64 = type_prefix + image_64 | |
# Get the image filename | |
filename = "/tmp/" + url.substring( url.lastIndexOf('/') + 1 ) | |
# Create a WriteStream for the image | |
out = fs.createWriteStream(filename) | |
# Save it | |
out.write(image) | |
# out.write(body) | |
out.end() | |
# Get the image dimensions using GraphicsMagick | |
im.identify filename, (err, data) -> | |
# Delete the tmp image | |
fs.unlink(filename) | |
# Error getting dimensions | |
if err | |
res.send("Error getting image dimensions", 400) | |
else | |
# The data to be returned | |
return_variable = | |
"width": data.width | |
"height": data.height | |
"data": image_64 | |
# Stringifiy the return variable and wrap it in the callback for JSONP compatibility | |
return_variable = callback + "(" + JSON.stringify(return_variable) + ");" | |
# Set the headers as OK and JS | |
res.writeHead(200, 'Content-Type': 'application/javascript; charset=UTF-8') | |
# Return the data | |
res.end(return_variable) | |
else | |
res.send("This file type is not supported", 400) | |
else | |
res.send("Third-party server error", response.statusCode) | |
else | |
res.send("No URL or no callback was specified. These are required", 400) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment