0
# JPEG Encoding
1
2
Encoding functionality for converting numpy arrays to JPEG data with comprehensive quality control, subsampling options, various pixel format support, progressive encoding, and in-place encoding for memory efficiency.
3
4
## Capabilities
5
6
### Standard Encoding
7
8
Encode numpy arrays to JPEG format with full control over quality, subsampling, pixel formats, and encoding flags.
9
10
```python { .api }
11
def encode(
12
img_array: np.ndarray,
13
quality: int = 85,
14
pixel_format: int = TJPF_BGR,
15
jpeg_subsample: int = TJSAMP_422,
16
flags: int = 0,
17
dst: bytearray | None = None
18
) -> bytes | tuple[bytearray, int]:
19
"""
20
Encode numpy array to JPEG memory buffer.
21
22
Args:
23
img_array: Input image array (height, width, channels)
24
quality: JPEG quality level (1-100, higher = better quality)
25
pixel_format: Input pixel format (TJPF_* constants)
26
jpeg_subsample: Chroma subsampling (TJSAMP_* constants)
27
flags: Encoding flags (TJFLAG_* constants)
28
dst: Optional pre-allocated buffer for in-place encoding
29
30
Returns:
31
bytes: JPEG data (if dst=None)
32
tuple[bytearray, int]: (buffer, actual_size) if dst provided
33
"""
34
```
35
36
### YUV Encoding
37
38
Encode from YUV format data directly to JPEG, useful when working with video data or avoiding color space conversions.
39
40
```python { .api }
41
def encode_from_yuv(
42
img_array: np.ndarray,
43
height: int,
44
width: int,
45
quality: int = 85,
46
jpeg_subsample: int = TJSAMP_420,
47
flags: int = 0
48
) -> bytes:
49
"""
50
Encode YUV array to JPEG memory buffer.
51
52
Args:
53
img_array: YUV image data as contiguous array
54
height: Image height in pixels
55
width: Image width in pixels
56
quality: JPEG quality level (1-100)
57
jpeg_subsample: Chroma subsampling (TJSAMP_* constants)
58
flags: Encoding flags (TJFLAG_* constants)
59
60
Returns:
61
bytes: JPEG data
62
"""
63
```
64
65
## Constants
66
67
### Quality Levels
68
69
Quality parameter ranges from 1-100:
70
- **1-30**: Low quality, high compression, small file sizes
71
- **31-60**: Medium quality, moderate compression
72
- **61-85**: Good quality, balanced compression (default: 85)
73
- **86-95**: High quality, lower compression
74
- **96-100**: Maximum quality, minimal compression, large files
75
76
### Subsampling Options
77
78
```python { .api }
79
TJSAMP_444: int # 4:4:4 - No subsampling (best quality, largest size)
80
TJSAMP_422: int # 4:2:2 - Horizontal subsampling (default)
81
TJSAMP_420: int # 4:2:0 - Both horizontal and vertical subsampling
82
TJSAMP_GRAY: int # Grayscale encoding
83
TJSAMP_440: int # 4:4:0 - Vertical subsampling
84
TJSAMP_411: int # 4:1:1 - High horizontal subsampling
85
TJSAMP_441: int # 4:4:1 - Minimal subsampling
86
```
87
88
### Encoding Flags
89
90
```python { .api }
91
TJFLAG_PROGRESSIVE: int # Progressive JPEG encoding
92
TJFLAG_FASTDCT: int # Fast DCT (lower quality, faster)
93
TJFLAG_ACCURATEDCT: int # Accurate DCT (higher quality, slower)
94
TJFLAG_BOTTOMUP: int # Bottom-up pixel order
95
```
96
97
### Pixel Formats
98
99
```python { .api }
100
TJPF_RGB: int # RGB pixel format
101
TJPF_BGR: int # BGR pixel format (OpenCV default)
102
TJPF_RGBX: int # RGBX pixel format
103
TJPF_BGRX: int # BGRX pixel format
104
TJPF_XBGR: int # XBGR pixel format
105
TJPF_XRGB: int # XRGB pixel format
106
TJPF_GRAY: int # Grayscale pixel format
107
TJPF_RGBA: int # RGBA pixel format
108
TJPF_BGRA: int # BGRA pixel format
109
TJPF_ABGR: int # ABGR pixel format
110
TJPF_ARGB: int # ARGB pixel format
111
TJPF_CMYK: int # CMYK pixel format
112
```
113
114
## Usage Examples
115
116
### Basic Encoding
117
118
```python
119
import numpy as np
120
from turbojpeg import TurboJPEG
121
122
jpeg = TurboJPEG()
123
124
# Create sample image data
125
image = np.random.randint(0, 256, (480, 640, 3), dtype=np.uint8)
126
127
# Encode with default settings (quality=85, BGR, 4:2:2 subsampling)
128
jpeg_data = jpeg.encode(image)
129
130
# Save to file
131
with open('output.jpg', 'wb') as f:
132
f.write(jpeg_data)
133
```
134
135
### Quality Control
136
137
```python
138
# High quality encoding
139
high_quality = jpeg.encode(image, quality=95)
140
141
# Low quality encoding (smaller file size)
142
low_quality = jpeg.encode(image, quality=30)
143
144
# Maximum quality
145
max_quality = jpeg.encode(image, quality=100)
146
147
print(f"High quality size: {len(high_quality)} bytes")
148
print(f"Low quality size: {len(low_quality)} bytes")
149
print(f"Max quality size: {len(max_quality)} bytes")
150
```
151
152
### Subsampling Options
153
154
```python
155
from turbojpeg import TJSAMP_444, TJSAMP_420, TJSAMP_GRAY
156
157
# No subsampling (best quality, largest size)
158
no_subsample = jpeg.encode(image, jpeg_subsample=TJSAMP_444)
159
160
# 4:2:0 subsampling (smaller file, web standard)
161
subsample_420 = jpeg.encode(image, jpeg_subsample=TJSAMP_420)
162
163
# Grayscale encoding
164
grayscale = jpeg.encode(image, jpeg_subsample=TJSAMP_GRAY)
165
166
print(f"4:4:4 size: {len(no_subsample)} bytes")
167
print(f"4:2:0 size: {len(subsample_420)} bytes")
168
print(f"Grayscale size: {len(grayscale)} bytes")
169
```
170
171
### Progressive Encoding
172
173
```python
174
from turbojpeg import TJFLAG_PROGRESSIVE
175
176
# Progressive JPEG (loads incrementally in browsers)
177
progressive_jpeg = jpeg.encode(
178
image,
179
quality=90,
180
flags=TJFLAG_PROGRESSIVE
181
)
182
183
with open('progressive.jpg', 'wb') as f:
184
f.write(progressive_jpeg)
185
```
186
187
### Pixel Format Handling
188
189
```python
190
from turbojpeg import TJPF_RGB, TJPF_GRAY
191
192
# RGB image (from PIL/Pillow)
193
rgb_image = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]], dtype=np.uint8)
194
rgb_image = rgb_image.reshape(1, 3, 3) # 1x3 image
195
rgb_jpeg = jpeg.encode(rgb_image, pixel_format=TJPF_RGB)
196
197
# Grayscale image
198
gray_image = np.random.randint(0, 256, (100, 100, 1), dtype=np.uint8)
199
gray_jpeg = jpeg.encode(gray_image, pixel_format=TJPF_GRAY)
200
```
201
202
### In-Place Encoding
203
204
```python
205
# Calculate required buffer size
206
buffer_size = jpeg.buffer_size(image)
207
print(f"Required buffer size: {buffer_size} bytes")
208
209
# Pre-allocate buffer
210
buffer = bytearray(buffer_size)
211
212
# Encode in-place
213
result, actual_size = jpeg.encode(image, dst=buffer)
214
215
# result is the same buffer object
216
assert result is buffer
217
218
# Write only the used portion
219
with open('inplace.jpg', 'wb') as f:
220
f.write(buffer[:actual_size])
221
222
print(f"Actual encoded size: {actual_size} bytes")
223
```
224
225
### YUV Encoding
226
227
```python
228
# Encode from YUV data (e.g., from video processing)
229
yuv_data = np.random.randint(0, 256, (480*640*3//2,), dtype=np.uint8)
230
231
yuv_jpeg = jpeg.encode_from_yuv(
232
yuv_data,
233
height=480,
234
width=640,
235
quality=85,
236
jpeg_subsample=TJSAMP_420
237
)
238
239
with open('from_yuv.jpg', 'wb') as f:
240
f.write(yuv_jpeg)
241
```
242
243
### Performance Optimization
244
245
```python
246
from turbojpeg import TJFLAG_FASTDCT
247
248
# Fast encoding (lower quality, higher speed)
249
fast_jpeg = jpeg.encode(
250
image,
251
quality=75,
252
flags=TJFLAG_FASTDCT
253
)
254
255
# Accurate encoding (higher quality, slower)
256
from turbojpeg import TJFLAG_ACCURATEDCT
257
258
accurate_jpeg = jpeg.encode(
259
image,
260
quality=85,
261
flags=TJFLAG_ACCURATEDCT
262
)
263
```