Skip to content

Commit

Permalink
Create pixbuf from data
Browse files Browse the repository at this point in the history
  • Loading branch information
can-lehmann committed Feb 26, 2023
1 parent a8c7cbd commit cd36e37
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
6 changes: 6 additions & 0 deletions owlkettle/gtk.nim
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,12 @@ proc gdk_clipboard_set_text*(clipboard: GdkClipboard, text: cstring, length: cin
proc gdk_pixbuf_new*(colorspace: GdkColorspace,
hasAlpha: cbool,
bitsPerSample, w, h: cint): GdkPixbuf
proc gdk_pixbuf_new_from_data*(pixels: pointer,
colorspace: GdkColorspace,
hasAlpha: cbool,
bitsPerSample, w, h, stride: cint,
destroy: proc(pixels, data: pointer) {.cdecl.},
destroyData: pointer): GdkPixbuf
proc gdk_pixbuf_new_from_file*(path: cstring, error: ptr GError): GdkPixbuf
proc gdk_pixbuf_new_from_file_at_scale*(path: cstring,
w, h: cint,
Expand Down
29 changes: 28 additions & 1 deletion owlkettle/widgets.nim
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ proc newPixbuf(gdk: GdkPixbuf): Pixbuf =
result.gdk = gdk

proc newPixbuf*(width, height: int,
bitsPerSample: int,
bitsPerSample: int = 8,
hasAlpha: bool = false,
colorspace: Colorspace = ColorspaceRgb): Pixbuf =
result = newPixbuf(gdk_pixbuf_new(
Expand All @@ -456,6 +456,33 @@ proc newPixbuf*(width, height: int,
height.cint
))

proc newPixbuf*(width, height: int,
data: openArray[uint8],
bitsPerSample: int = 8,
hasAlpha: bool = false,
colorspace: Colorspace = ColorspaceRgb): Pixbuf =
let channels = if hasAlpha: 4 else: 3
assert width * height * channels * (bitsPerSample div 8) == data.len

proc destroy(pixels: pointer, data: pointer) {.cdecl.} =
dealloc(pixels)

let buffer = cast[ptr UncheckedArray[uint8]](alloc(data.len))
if data.len > 0:
copyMem(buffer, data[0].unsafeAddr, data.len)

result = newPixbuf(gdk_pixbuf_new_from_data(
buffer,
GdkColorspace(ord(colorspace)),
cbool(ord(hasAlpha)),
bitsPerSample.cint,
width.cint,
height.cint,
cint(channels * width * (bitsPerSample div 8)),
destroy,
nil
))

proc loadPixbuf*(path: string): Pixbuf =
var error = GError(nil)
let pixbuf = gdk_pixbuf_new_from_file(path.cstring, error.addr)
Expand Down

0 comments on commit cd36e37

Please sign in to comment.