Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request: image.to_bytes() function #25

Open
IagoBeuller opened this issue Dec 22, 2022 · 0 comments
Open

Request: image.to_bytes() function #25

IagoBeuller opened this issue Dec 22, 2022 · 0 comments

Comments

@IagoBeuller
Copy link

IagoBeuller commented Dec 22, 2022

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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant