Created
April 19, 2022 10:56
-
-
Save Yepoleb/f041a88964e618d629d36caf8d1fbf01 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dynlib | |
type | |
PixelRgba = object | |
r, g, b, a: uint8 | |
Image = ref object of RootObj | |
width: int | |
height: int | |
ImageRgba = ref object of Image | |
surface: seq[PixelRgba] | |
type | |
TjHandle = pointer | |
TJPF = enum | |
UNKNOWN = -1, | |
RGB = 0, BGR, RGBX, BGRX, XBGR, XRGB, GRAY, RGBA, BGRA, ABGR, ARGB, CMYK | |
var libJpeg: LibHandle = nil | |
var tjDecompressor: TjHandle = nil | |
var procTjInitDecompress: (proc(): TjHandle {.cdecl.}) | |
var procTjDecompress2: (proc(handle: TjHandle, jpegBuf: cstring, jpegSize: culong, dstBuf: pointer, width: cint, pitch: cint, height: cint, pixelFormat: cint, flags: cint): cint {.cdecl.}) | |
var procTjDecompressHeader3: (proc(handle: TjHandle, jpegBuf: cstring, jpegSize: culong, width: ptr cint, height: ptr cint, jpegSubsamp: ptr cint, jpegColorspace: ptr cint): cint {.cdecl.}) | |
proc initLibJpeg() = | |
if libJpeg != nil: | |
return | |
libJpeg = loadLib("libturbojpeg.so.0") | |
assert libJpeg != nil | |
procTjInitDecompress = cast[type(procTjInitDecompress)]( | |
checkedSymAddr(libJpeg, "tjInitDecompress")) | |
procTjDecompress2 = cast[type(procTjDecompress2)]( | |
checkedSymAddr(libJpeg, "tjDecompress2")) | |
procTjDecompressHeader3 = cast[type(procTjDecompressHeader3)]( | |
checkedSymAddr(libJpeg, "tjDecompressHeader3")) | |
tjDecompressor = procTjInitDecompress() | |
proc openJpegRgba(f: var File): ImageRgba = | |
initLibJpeg() | |
new result | |
var jpegBuf: string = f.readAll() | |
var width, height, jpegSubsamp, jpegColorspace: cint | |
discard procTjDecompressHeader3( | |
tjDecompressor, jpegBuf.cstring, jpegBuf.len.culong, | |
width.addr, height.addr, jpegSubsamp.addr, jpegColorspace.addr) | |
result.width = width.int | |
result.height = height.int | |
result.surface = newSeq[PixelRgba](width * height) | |
discard procTjDecompress2( | |
tjDecompressor, jpegBuf.cstring, jpegBuf.len.culong, result.surface[0].addr, | |
width, 0, height, TJPF.RGBA.cint, 0) | |
var f = open("../test.jpeg") | |
var img = openJpegRgba(f) | |
echo img.surface |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment