pixie/src/pixie.nim

62 lines
1.8 KiB
Nim
Raw Normal View History

2020-11-21 05:50:13 +00:00
import pixie/images, pixie/masks, pixie/paths, pixie/common, pixie/blends,
2020-11-29 21:46:29 +00:00
pixie/fileformats/bmp, pixie/fileformats/png, pixie/fileformats/jpg,
2020-11-21 23:45:02 +00:00
flatty/binny, os
2020-11-21 04:34:57 +00:00
export images, masks, paths, common, blends
2020-11-20 03:44:24 +00:00
2020-11-21 04:34:57 +00:00
type
FileFormat* = enum
2020-11-21 23:45:02 +00:00
ffPng, ffBmp, ffJpg
2020-11-21 04:34:57 +00:00
2020-11-20 03:44:24 +00:00
proc toMask*(image: Image): Mask =
## Converts an Image to a Mask.
result = newMask(image.width, image.height)
for i in 0 ..< image.data.len:
result.data[i] = image.data[i].a
proc toImage*(mask: Mask): Image =
## Converts a Mask to Image.
result = newImage(mask.width, mask.height)
for i in 0 ..< mask.data.len:
result.data[i].a = mask.data[i]
2020-11-21 04:34:57 +00:00
2020-11-21 05:09:52 +00:00
proc decodeImage*(data: string | seq[uint8]): Image =
2020-11-21 04:34:57 +00:00
## Loads an image from a memory.
2020-11-21 23:45:02 +00:00
if data.len > 8 and data.readUint64(0) == cast[uint64](pngSignature):
decodePng(data)
elif data.len > 2 and data.readUint16(0) == cast[uint16](jpgStartOfImage):
decodeJpg(data)
elif data.len > 2 and data.readStr(0, 2) == "BM":
decodeBmp(data)
else:
raise newException(PixieError, "Unsupported image file format")
2020-11-21 04:34:57 +00:00
proc readImage*(filePath: string): Image =
## Loads an image from a file.
decodeImage(readFile(filePath))
2020-11-21 05:09:52 +00:00
proc encodeImage*(image: Image, fileFormat: FileFormat): string =
2020-11-21 23:45:02 +00:00
## Encodes an image into memory.
2020-11-21 04:34:57 +00:00
case fileFormat:
of ffPng:
image.encodePng()
2020-11-21 23:45:02 +00:00
of ffJpg:
image.encodeJpg()
2020-11-21 04:34:57 +00:00
of ffBmp:
image.encodeBmp()
proc writeFile*(image: Image, filePath: string, fileFormat: FileFormat) =
## Writes an image to a file.
writeFile(filePath, image.encodeImage(fileFormat))
2020-11-21 18:34:57 +00:00
proc writeFile*(image: Image, filePath: string) =
## Writes an image to a file.
let fileFormat = case splitFile(filePath).ext:
2020-11-22 02:02:57 +00:00
of ".png": ffPng
of ".bmp": ffBmp
of ".jpg": ffJpg
2020-11-22 02:05:48 +00:00
of ".jpeg": ffJpg
2020-11-21 23:45:02 +00:00
else:
2020-11-22 02:05:48 +00:00
raise newException(PixieError, "Unsupported image file extension")
2020-11-21 23:45:02 +00:00
image.writeFile(filePath, fileformat)