Create Image type.

This commit is contained in:
SeanOMik 2020-06-18 22:01:22 -05:00
parent a665d00030
commit 4bf2ad785e
No known key found for this signature in database
GPG Key ID: FA4D55AC05268A88
1 changed files with 27 additions and 0 deletions

27
src/image.nim Normal file
View File

@ -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}")