or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-structures.mdimage-processing.mdindex.mdqrcode-support.mdreading-decoding.mdresult-processing.mdwriting-encoding.md

writing-encoding.mddocs/

0

# Writing and Encoding

1

2

Core barcode writing and encoding functionality providing the primary interface for generating barcode images from text content across all supported formats.

3

4

## Capabilities

5

6

### Writer Interface

7

8

Primary interface that all barcode writers implement for encoding operations.

9

10

```java { .api }

11

/**

12

* Main interface for barcode encoding implementations

13

*/

14

public interface Writer {

15

/**

16

* Encode content as a barcode with basic parameters

17

* @param contents Text content to encode

18

* @param format Barcode format to generate

19

* @param width Preferred width in pixels

20

* @param height Preferred height in pixels

21

* @return BitMatrix representing the encoded barcode

22

* @throws WriterException if content cannot be encoded

23

*/

24

BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException;

25

26

/**

27

* Encode content as a barcode with configuration hints

28

* @param contents Text content to encode

29

* @param format Barcode format to generate

30

* @param width Preferred width in pixels

31

* @param height Preferred height in pixels

32

* @param hints Encoding configuration options

33

* @return BitMatrix representing the encoded barcode

34

* @throws WriterException if content cannot be encoded

35

*/

36

BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException;

37

}

38

```

39

40

### MultiFormatWriter

41

42

Main entry point for encoding that delegates to format-specific writers based on the requested barcode format.

43

44

```java { .api }

45

/**

46

* Factory class for encoding barcodes in multiple formats

47

* Delegates to appropriate format-specific writer implementations

48

*/

49

public final class MultiFormatWriter implements Writer {

50

/**

51

* Standard constructor

52

*/

53

public MultiFormatWriter();

54

55

// Supports all major formats:

56

// 2D: QR_CODE, DATA_MATRIX, AZTEC, PDF_417

57

// 1D: CODE_128, CODE_39, CODE_93, EAN_8, EAN_13, UPC_A, UPC_E, ITF, CODABAR

58

}

59

```

60

61

**Usage Examples:**

62

63

```java

64

import com.google.zxing.*;

65

import com.google.zxing.common.BitMatrix;

66

import java.util.Map;

67

import java.util.HashMap;

68

69

// Basic encoding

70

MultiFormatWriter writer = new MultiFormatWriter();

71

BitMatrix qrCode = writer.encode("Hello World", BarcodeFormat.QR_CODE, 300, 300);

72

73

// Encoding with hints

74

Map<EncodeHintType, Object> hints = new HashMap<>();

75

hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

76

hints.put(EncodeHintType.MARGIN, 2);

77

78

BitMatrix dataMatrix = writer.encode(

79

"Complex content with UTF-8: éñ中文",

80

BarcodeFormat.DATA_MATRIX,

81

200,

82

200,

83

hints

84

);

85

86

// Generate different formats

87

BitMatrix code128 = writer.encode("123456789", BarcodeFormat.CODE_128, 400, 100);

88

BitMatrix pdf417 = writer.encode("Document data", BarcodeFormat.PDF_417, 500, 200);

89

```

90

91

### Format-Specific Writers

92

93

Individual writers for specific barcode formats when you need format-specific configuration.

94

95

```java { .api }

96

// QR Code

97

public final class QRCodeWriter implements Writer {

98

public QRCodeWriter();

99

}

100

101

// Data Matrix

102

public final class DataMatrixWriter implements Writer {

103

public DataMatrixWriter();

104

}

105

106

// Aztec

107

public final class AztecWriter implements Writer {

108

public AztecWriter();

109

}

110

111

// PDF417

112

public final class PDF417Writer implements Writer {

113

public PDF417Writer();

114

}

115

116

// 1D Barcode Writers

117

public final class Code128Writer extends OneDimensionalCodeWriter {

118

public Code128Writer();

119

}

120

121

public final class Code39Writer extends OneDimensionalCodeWriter {

122

public Code39Writer();

123

}

124

125

public final class EAN13Writer extends OneDimensionalCodeWriter {

126

public EAN13Writer();

127

}

128

129

public final class UPCAWriter extends OneDimensionalCodeWriter {

130

public UPCAWriter();

131

}

132

133

public abstract class OneDimensionalCodeWriter implements Writer {

134

// Base class for all 1D barcode writers

135

public abstract boolean[] encode(String contents);

136

}

137

```

138

139

### Encoding Hints

140

141

Configuration options to control encoding behavior and output characteristics.

142

143

```java { .api }

144

public enum EncodeHintType {

145

/**

146

* Error correction level for formats that support it

147

* QR Code: ErrorCorrectionLevel (L, M, Q, H)

148

* PDF417: Integer (0-8)

149

* Aztec: Integer (percentage 0-100)

150

*/

151

ERROR_CORRECTION,

152

153

/**

154

* Character encoding for input text

155

* Value: String (charset name like "UTF-8", "ISO-8859-1")

156

*/

157

CHARACTER_SET,

158

159

/**

160

* Shape constraint for Data Matrix symbols

161

* Value: SymbolShapeHint (FORCE_NONE, FORCE_SQUARE, FORCE_RECTANGLE)

162

*/

163

DATA_MATRIX_SHAPE,

164

165

/**

166

* Force compact Data Matrix encoding

167

* Value: Boolean

168

*/

169

DATA_MATRIX_COMPACT,

170

171

/**

172

* Margin size around the barcode

173

* Value: Integer (number of pixels or modules)

174

*/

175

MARGIN,

176

177

/**

178

* Enable compact PDF417 mode

179

* Value: Boolean

180

*/

181

PDF417_COMPACT,

182

183

/**

184

* PDF417 compaction mode

185

* Value: Compaction (AUTO, TEXT, BYTE, NUMERIC)

186

*/

187

PDF417_COMPACTION,

188

189

/**

190

* PDF417 dimensions (columns and rows)

191

* Value: Dimensions object

192

*/

193

PDF417_DIMENSIONS,

194

195

/**

196

* Enable automatic ECI detection for PDF417

197

* Value: Boolean

198

*/

199

PDF417_AUTO_ECI,

200

201

/**

202

* Number of layers for Aztec codes

203

* Value: Integer (1-32 for compact, 1-32 for full)

204

*/

205

AZTEC_LAYERS,

206

207

/**

208

* QR Code version (size)

209

* Value: Integer (1-40)

210

*/

211

QR_VERSION,

212

213

/**

214

* QR Code mask pattern

215

* Value: Integer (0-7)

216

*/

217

QR_MASK_PATTERN,

218

219

/**

220

* Force compact QR Code mode

221

* Value: Boolean

222

*/

223

QR_COMPACT,

224

225

/**

226

* Enable GS1 formatting

227

* Value: Boolean

228

*/

229

GS1_FORMAT,

230

231

/**

232

* Force specific Code 128 code set

233

* Value: String ("A", "B", "C")

234

*/

235

FORCE_CODE_SET,

236

237

/**

238

* Force C40 encoding for Data Matrix

239

* Value: Boolean

240

*/

241

FORCE_C40,

242

243

/**

244

* Enable compact Code 128 encoding

245

* Value: Boolean

246

*/

247

CODE128_COMPACT

248

}

249

```

250

251

**Hint Usage Examples:**

252

253

```java

254

Map<EncodeHintType, Object> hints = new HashMap<>();

255

256

// QR Code with high error correction

257

hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

258

hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

259

hints.put(EncodeHintType.MARGIN, 4);

260

261

BitMatrix qrCode = writer.encode("Text", BarcodeFormat.QR_CODE, 300, 300, hints);

262

263

// Data Matrix with square shape constraint

264

Map<EncodeHintType, Object> dmHints = new HashMap<>();

265

dmHints.put(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_SQUARE);

266

dmHints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

267

268

BitMatrix dm = writer.encode("Data", BarcodeFormat.DATA_MATRIX, 200, 200, dmHints);

269

270

// PDF417 with specific configuration

271

Map<EncodeHintType, Object> pdfHints = new HashMap<>();

272

pdfHints.put(EncodeHintType.ERROR_CORRECTION, 2);

273

pdfHints.put(EncodeHintType.PDF417_COMPACT, Boolean.TRUE);

274

pdfHints.put(EncodeHintType.MARGIN, 10);

275

276

BitMatrix pdf = writer.encode("Document", BarcodeFormat.PDF_417, 400, 200, pdfHints);

277

```

278

279

### BitMatrix Output

280

281

The result of all encoding operations, representing the barcode as a 2D boolean matrix.

282

283

```java { .api }

284

/**

285

* 2D bit matrix representation of encoded barcode

286

*/

287

public final class BitMatrix implements Cloneable {

288

/**

289

* Get the width of the matrix

290

* @return Width in pixels/modules

291

*/

292

public int getWidth();

293

294

/**

295

* Get the height of the matrix

296

* @return Height in pixels/modules

297

*/

298

public int getHeight();

299

300

/**

301

* Get the value at specific coordinates

302

* @param x X coordinate

303

* @param y Y coordinate

304

* @return true if the module is set (black), false if unset (white)

305

*/

306

public boolean get(int x, int y);

307

308

/**

309

* Get an entire row as a BitArray

310

* @param y Row index

311

* @param row Optional pre-allocated BitArray to reuse

312

* @return BitArray representing the row

313

*/

314

public BitArray getRow(int y, BitArray row);

315

316

/**

317

* Create a deep copy of the matrix

318

* @return Cloned BitMatrix

319

*/

320

public BitMatrix clone();

321

}

322

```

323

324

**BitMatrix Usage Examples:**

325

326

```java

327

// Encode and convert to image

328

BitMatrix matrix = writer.encode("Data", BarcodeFormat.QR_CODE, 300, 300);

329

330

// Convert to BufferedImage (common approach)

331

BufferedImage image = new BufferedImage(

332

matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);

333

334

for (int x = 0; x < matrix.getWidth(); x++) {

335

for (int y = 0; y < matrix.getHeight(); y++) {

336

image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);

337

}

338

}

339

340

// Save to file

341

ImageIO.write(image, "PNG", new File("barcode.png"));

342

343

// Print as ASCII art

344

for (int y = 0; y < matrix.getHeight(); y++) {

345

for (int x = 0; x < matrix.getWidth(); x++) {

346

System.out.print(matrix.get(x, y) ? "██" : " ");

347

}

348

System.out.println();

349

}

350

```

351

352

### Writer Exception Handling

353

354

Exception thrown when encoding fails due to invalid content or configuration.

355

356

```java { .api }

357

/**

358

* Exception thrown when barcode encoding fails

359

*/

360

public final class WriterException extends Exception {

361

/**

362

* Standard constructor with message

363

* @param message Error description

364

*/

365

public WriterException(String message);

366

367

/**

368

* Constructor with message and cause

369

* @param message Error description

370

* @param cause Underlying exception

371

*/

372

public WriterException(String message, Throwable cause);

373

374

/**

375

* Constructor with cause only

376

* @param cause Underlying exception

377

*/

378

public WriterException(Throwable cause);

379

}

380

```

381

382

**Exception Handling Examples:**

383

384

```java

385

try {

386

BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, 300, 300);

387

} catch (WriterException e) {

388

System.err.println("Encoding failed: " + e.getMessage());

389

390

// Common causes:

391

// - Content too long for format

392

// - Invalid characters for format

393

// - Incompatible hint values

394

// - Format doesn't support requested size

395

}

396

397

// Validate content before encoding

398

public boolean canEncode(String content, BarcodeFormat format) {

399

try {

400

writer.encode(content, format, 100, 100);

401

return true;

402

} catch (WriterException e) {

403

return false;

404

}

405

}

406

```

407

408

### Format Capabilities and Limitations

409

410

Each barcode format has specific content and size limitations:

411

412

#### QR Code

413

- **Content**: Any text, binary data

414

- **Character sets**: UTF-8, ISO-8859-1, others via hints

415

- **Max capacity**: ~4,296 alphanumeric characters (varies by error correction)

416

- **Error correction**: L (~7%), M (~15%), Q (~25%), H (~30%)

417

418

#### Data Matrix

419

- **Content**: Any text, binary data

420

- **Character sets**: UTF-8, ASCII, others

421

- **Max capacity**: ~2,335 alphanumeric characters

422

- **Sizes**: Square (10x10 to 144x144) or rectangular (8x18 to 16x48)

423

424

#### Code 128

425

- **Content**: All ASCII characters (0-127)

426

- **Variable length**: Yes

427

- **Check digit**: Automatic

428

- **Optimal for**: Alphanumeric content, shipping labels

429

430

#### EAN-13/UPC-A

431

- **Content**: Numeric only

432

- **Length**: Fixed (13 digits for EAN-13, 12 for UPC-A)

433

- **Check digit**: Automatic

434

- **Usage**: Retail products

435

436

```java

437

// Format-specific encoding examples

438

Map<EncodeHintType, Object> hints = new HashMap<>();

439

440

// QR Code with maximum error correction

441

hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

442

BitMatrix qr = writer.encode("https://example.com", BarcodeFormat.QR_CODE, 300, 300, hints);

443

444

// Code 128 for alphanumeric content

445

BitMatrix code128 = writer.encode("ABC123", BarcodeFormat.CODE_128, 400, 100);

446

447

// EAN-13 for product codes (check digit calculated automatically)

448

BitMatrix ean13 = writer.encode("123456789012", BarcodeFormat.EAN_13, 300, 150);

449

450

// Data Matrix with rectangular shape

451

hints.clear();

452

hints.put(EncodeHintType.DATA_MATRIX_SHAPE, SymbolShapeHint.FORCE_RECTANGLE);

453

BitMatrix dm = writer.encode("Data", BarcodeFormat.DATA_MATRIX, 200, 100, hints);

454

```

455

456

## Performance and Best Practices

457

458

### Content Optimization

459

- Use appropriate character sets to minimize encoding size

460

- Consider format-specific optimizations (e.g., numeric mode for QR codes)

461

- Validate content length against format limits

462

463

### Size Recommendations

464

- Maintain adequate quiet zones (margins) around barcodes

465

- Consider minimum module sizes for print quality

466

- Test readability at target print/display sizes

467

468

### Error Correction Strategy

469

- Use higher error correction for damaged/degraded environments

470

- Balance error correction against data capacity needs

471

- Consider environmental factors (print quality, scanning conditions)