How to create an image from canvas data?

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

There I try to create an NSBitmapImageRep object , then save it in the image format that the user wants.

This is my code so far (the function receives a WebScriptObject as an 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 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 does not seem to go through the function initWithBitmapDataPlanes, but gives no errors.

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

Edit

Phrogz, : , getImageData, putImageData toDataURL, URL- . setimagedata URL- , dataOfType: error: :

def dataOfType(type, error:outError)
    workspace = NSWorkspace.sharedWorkspace
    if workspace.type(type, conformsToType: "public.image")
        @data_url[ /(?<=,).+/ ].unpack("m").first
    end
end

- :

class NSString
    def writeToURL(url, options: opts, error: error)
        File.open(url.path, "w") {|f| f << self }
    end
end

Cocoa , , NSData .

, , , , . , NSBitmapImageRep. , , , , , .

+3
1

getImageData Canvas.toDataURL. PNG ( JPEG), base64. base64, , , .

. , , . , , :

base64, base64 ruby ​​library decode64. , , :

def decode64(str)
  str.unpack("m").first
end

2. , toDataURL, Ruby, :

require 'base64'
data_only = data_url[ /(?<=,).+/ ] # Find everything after the first comma
File.open( 'foo.png', 'w' ){ |f| f << Base64.decode64( data_only ) }
+3

Source: https://habr.com/ru/post/1784362/


All Articles