1 module jpeg_turbod.compress;
2 
3 import jpeg_turbod.libjpeg_turbo;
4 
5 class Compressor
6 {
7     private
8     {
9         tjhandle compressor;
10         enum int rgbPixelSize = 3;
11     }
12 
13     this()
14     {
15         compressor = tjInitCompress();
16     }
17 
18     ~this()
19     {
20         tjDestroy(compressor);
21     }
22 
23     final char[] errorInfo()
24     {
25         import std.string : fromStringz;
26 
27         return fromStringz(tjGetErrorStr2(compressor));
28     }
29 
30     final bool compress(in ubyte[] pixels, ref ubyte[] jpeg, int width, int height, int quality = 80)
31     in
32     {
33         assert(quality >= 0 && quality <= 100, "JPEG quality must be in the range [0, 100].");
34     }
35     do
36     {
37         int pitch = 0; // jpeg_turbo will comput the pitch using width and the pixel format.
38         ulong jpegSize = pixels.length;
39         ubyte* allocBuffer;
40 
41         allocBuffer = tjAlloc(cast(int) jpegSize);
42 
43         int result = tjCompress2(compressor, pixels.ptr, width, pitch, height, TJPF.TJPF_RGB,
44                 &(allocBuffer), &jpegSize, TJSAMP.TJSAMP_444, quality, TJFLAG_ACCURATEDCT);
45 
46         if (result == 0)
47         {
48             jpeg = allocBuffer[0 .. jpegSize];
49             return true;
50         }
51         else
52         {
53             return false;
54         }
55     }
56 }