How to create an image from canvas data?

Posted by Jakub Hampl on Stack Overflow See other posts from Stack Overflow or by Jakub Hampl
Published on 2011-01-09T11:59:32Z Indexed on 2011/01/10 0:53 UTC
Read the original article Hit count: 199

Filed under:
|
|
|
|

In my application I am trying to save an arbitrary part of a rendered HTML canvas to an image file. In my Javascript I call ctx.getImageData(x, y, w, h) and pass the resulting object to my macruby code (though if you know a solution in objc I am also very interested).

There I'm trying to create a NSBitmapImageRep object so that I can then save to an image format the user desires.

This is my code so far (the function gets a WebScriptObject as it's argument):

def setimagedata(d)
    w =  d.valueForKey("width").to_i
    h =  d.valueForKey("height").to_i
    data = Pointer.new(:char, d.valueForKey("data").valueForKey("length").to_i)
    d.valueForKey("data").valueForKey("length").to_i.times do |i|
        data[i] = d.valueForKey("data").webScriptValueAtIndex(i).to_i
    end
    puts "data complete" # get's called
    @exported_image = NSBitmapImageRep.alloc.initWithBitmapDataPlanes(data,
        pixelsWide: w, pixelsHigh:h, bitsPerSample: 32,
        samplesPerPixel: 4, hasAlpha: true, isPlanar: false, 
        colorSpaceName: NSCalibratedRGBColorSpace, 
        bitmapFormat: NSAlphaNonpremultipliedBitmapFormat, 
        bytesPerRow: 0, bitsPerPixel: 0)
    puts "done" # doesn't get called
end

The code doesn't seem to get through the initWithBitmapDataPlanes function but gives no error.

My question is: what am I doing wrong? Is this approach reasonable (if not, what would be better?).

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about objective-c