Skip to content

Request: image.to_bytes() function #25

@IagoBeuller

Description

@IagoBeuller

I need the bytes of the images, for example, use them in pillow or pygame. Also "imageFromBytes(data: string): Image".

I've made this little library for making this feature for me, it gets the image data bytes as well the png file bytes.

import
    nimpy,
    pixie

pyExportModule("pixie_utils")

proc getImageBytes*(image: Image, format: string = "png"): string {.raises: [PixieError].} =
  # Gets the bytes from image.
  let encodeFormat = case format:
    of "png": PngFormat
    of "bmp": BmpFormat
    of "jpg", "jpeg": JpegFormat
    of "qoi": QoiFormat
    of "ppm": PpmFormat
    else:
      raise newException(PixieError, "Unsupported image format")

  result = image.encodeImage(encodeFormat)

proc getImageData*(image: Image): string {.raises: [].} =
  # Gets the image data as bytes.
  result = newString(image.width * image.height * 4)
  var
    i = 0
    rgba: ColorRGBA
  
  for color in image.data:
    rgba = color.rgba()
    result[i] = rgba.r.char
    result[i+1] = rgba.g.char
    result[i+2] = rgba.b.char
    result[i+3] = rgba.a.char
    i += 4

proc getImageBytes(image_ref: int, format: string = "png"): string {.exportpy: "getImageBytes".} =
    result = getImageBytes(cast[Image](image_ref), format)

proc getImageData(image_ref: int): string {.exportpy: "getImageData".} =
    result = getImageData(cast[Image](image_ref))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions