From 4bf2ad785e48721071865ba3a86ec91318bf2f4e Mon Sep 17 00:00:00 2001 From: SeanOMik Date: Thu, 18 Jun 2020 22:01:22 -0500 Subject: [PATCH] Create Image type. --- src/image.nim | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/image.nim diff --git a/src/image.nim b/src/image.nim new file mode 100644 index 0000000..53dc9b9 --- /dev/null +++ b/src/image.nim @@ -0,0 +1,27 @@ +import base64, streams, os, strformat + +type Image* = ref object + filepath*: string + extension: string + base64Encoded: string + +proc newImage*(filepath: string): Image = + ## Reads from a file that exists at `filepath`. It reads the image data, + ## and image extension for later use. + var imageStream = newFileStream(filepath, fmRead) + if (not isNil(imageStream)): + let data = imageStream.readALL() + + # Get the file's extension and remove the `.` from the start of it + result = Image( + extension: splitFile(filepath).ext.substr(1), + base64Encoded: encode(data), + filepath: filepath + ) + + imageStream.close() + else: + raise newException(IOError, "Failed to open file: " & filepath) + +proc imageToDataURI*(image: Image): string = + return fmt("data:image/{image.extension};base64,{image.base64Encoded}") \ No newline at end of file