Kotchasan Framework Documentation
Barcode Class - Barcode Generation
Barcode Class - Barcode Generation
The Barcode class is a tool for generating Code 128 barcodes in the Kotchasan Framework.
Namespace
namespace Kotchasan;Overview
The Barcode class is used to create standard Code 128 barcodes and output them as PNG images. It supports displaying text labels below the barcode with customizable fonts.
When to use:
- Need to generate barcodes for products
- Need product tracking system with barcodes
- Need price labels with barcodes
- Need inventory management system with barcodes
System Requirements
- PHP 7.4 or higher
- GD Extension (for image generation)
- Font file:
skin/fonts/thsarabunnew-webfont.ttf(for text display)
Class Properties
Public Properties
public string $font = ROOT_PATH.'skin/fonts/thsarabunnew-webfont.ttf';- Type: string
- Default:
ROOT_PATH.'skin/fonts/thsarabunnew-webfont.ttf' - Description: Path to the font file used to display text below the barcode. Can be changed after creating the instance
Private Properties
private int $height; // Barcode height
private int $bar_width = 1; // Width of each bar (pixels)
private int $width = 0; // Total barcode width
private array $datas; // Barcode bar data (array of 0/1)
private string $code; // Code converted to barcode
private int $fontSize = 0; // Font size for text display (0 = no text)ℹ️ Note: These properties are internal state and cannot be accessed externally
Constructor
protected function __construct(string $code, int $height, int $fontSize = 0)⚠️ Warning: Constructor is protected and cannot be called directly. Use factory method create() instead
Factory Methods
create()
Create Barcode instance (Factory method)
public static function create(
string $code,
int $height = 30,
int $fontSize = 0
): staticParameters:
$code(string, required) - Code to convert to barcode (supports letters, numbers, and special symbols per Code 128)$height(int, optional, default: 30) - Barcode height in pixels$fontSize(int, optional, default: 0) - Font size for text below barcode (0 = no text display)
Returns: Instance of Barcode class
Example:
use Kotchasan\Barcode;
// Create basic barcode (30px height, no text)
$barcode = Barcode::create('123456789');
// Create 50px height barcode with 12px text
$barcode = Barcode::create('PRODUCT001', 50, 12);
// Create large barcode with text
$barcode = Barcode::create('SKU-2024-001', 80, 14);Public Methods
toPng()
Generate barcode image as PNG format
public function toPng(): stringParameters: None
Returns: string - Binary PNG image data (can be saved as file or output directly)
Example:
use Kotchasan\Barcode;
// Create and display barcode in browser
$barcode = Barcode::create('123456789', 50, 12);
$imageData = $barcode->toPng();
header('Content-Type: image/png');
echo $imageData;Usage Examples
Example 1: Create and Save Basic Barcode
require_once 'load.php';
use Kotchasan\Barcode;
try {
// Create Barcode instance
$barcode = Barcode::create('123456789');
// Generate PNG image
$imageData = $barcode->toPng();
// Save as file
$result = file_put_contents('barcode_123456789.png', $imageData);
if ($result !== false) {
echo "Barcode generated successfully: {$result} bytes\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}Output:
Barcode generated successfully: 1234 bytesExample 2: Create Barcode with Text and Custom Font
use Kotchasan\Barcode;
// Create 60px height barcode with 14px text
$barcode = Barcode::create('PRODUCT-2024-001', 60, 14);
// Change font (optional)
$barcode->font = ROOT_PATH . 'skin/fonts/custom-font.ttf';
// Generate and save image
$imageData = $barcode->toPng();
file_put_contents('product_barcode.png', $imageData);
echo "Barcode with text generated\n";Example 3: Product Barcode Generation System
use Kotchasan\Barcode;
/**
* Function to generate product barcode by size
*/
function generateProductBarcode(string $productCode, string $size = 'medium'): string
{
// Define barcode sizes
$sizes = [
'small' => ['height' => 40, 'fontSize' => 10],
'medium' => ['height' => 60, 'fontSize' => 12],
'large' => ['height' => 80, 'fontSize' => 14]
];
$config = $sizes[$size] ?? $sizes['medium'];
// Create barcode
$barcode = Barcode::create(
$productCode,
$config['height'],
$config['fontSize']
);
return $barcode->toPng();
}
// Usage
$productCode = 'SKU-12345';
$barcodeImage = generateProductBarcode($productCode, 'large');
// Save file
file_put_contents("barcodes/{$productCode}.png", $barcodeImage);
echo "Generated barcode for product {$productCode}\n";Example 4: Complete Barcode Management System
use Kotchasan\Barcode;
/**
* Product Barcode Manager Class
*/
class BarcodeManager
{
private string $basePath;
public function __construct(string $basePath = 'barcodes/')
{
$this->basePath = rtrim($basePath, '/') . '/';
// Create folder if not exists
if (!is_dir($this->basePath)) {
mkdir($this->basePath, 0755, true);
}
}
/**
* Generate single barcode
*/
public function generate(string $code, array $options = []): array
{
$height = $options['height'] ?? 60;
$fontSize = $options['fontSize'] ?? 12;
$barcode = Barcode::create($code, $height, $fontSize);
// Change font if specified
if (isset($options['font'])) {
$barcode->font = $options['font'];
}
$imageData = $barcode->toPng();
return [
'code' => $code,
'data' => $imageData,
'size' => strlen($imageData)
];
}
/**
* Generate and save barcode
*/
public function save(string $code, array $options = []): array
{
$result = $this->generate($code, $options);
$filename = $options['filename'] ?? $code . '.png';
$filepath = $this->basePath . $filename;
$bytesWritten = file_put_contents($filepath, $result['data']);
return [
'success' => $bytesWritten !== false,
'code' => $code,
'filepath' => $filepath,
'filename' => $filename,
'size' => $bytesWritten
];
}
/**
* Generate multiple barcodes at once
*/
public function batchGenerate(array $codes, array $options = []): array
{
$results = [];
foreach ($codes as $code) {
$results[$code] = $this->save($code, $options);
}
return $results;
}
/**
* Check if barcode exists
*/
public function exists(string $code): bool
{
return file_exists($this->basePath . $code . '.png');
}
/**
* Delete barcode
*/
public function delete(string $code): bool
{
$filepath = $this->basePath . $code . '.png';
if (file_exists($filepath)) {
return unlink($filepath);
}
return false;
}
}
// BarcodeManager usage example
// Create manager
$manager = new BarcodeManager('storage/barcodes/');
// Generate single barcode
$result = $manager->save('PRODUCT001', [
'height' => 70,
'fontSize' => 14
]);
if ($result['success']) {
echo "Saved barcode at: {$result['filepath']}\n";
echo "File size: {$result['size']} bytes\n";
}
// Generate multiple barcodes
$productCodes = ['PROD001', 'PROD002', 'PROD003', 'PROD004', 'PROD005'];
$results = $manager->batchGenerate($productCodes, [
'height' => 60,
'fontSize' => 12
]);
echo "\nGenerated total: " . count($results) . " barcodes\n";
foreach ($results as $code => $result) {
if ($result['success']) {
echo "✓ {$code}: {$result['size']} bytes\n";
} else {
echo "✗ {$code}: Failed\n";
}
}Output:
Saved barcode at: storage/barcodes/PRODUCT001.png
File size: 1456 bytes
Generated total: 5 barcodes
✓ PROD001: 1234 bytes
✓ PROD002: 1256 bytes
✓ PROD003: 1245 bytes
✓ PROD004: 1267 bytes
✓ PROD005: 1289 bytesExample 5: Database Integration
use Kotchasan\Barcode;
/**
* Product Barcode System with Database
*/
class ProductBarcode
{
private $db;
private BarcodeManager $barcodeManager;
public function __construct($database)
{
$this->db = $database;
$this->barcodeManager = new BarcodeManager('public/barcodes/');
}
/**
* Create barcode for product
*/
public function createForProduct(int $productId): array
{
// Get product data
$product = $this->db->createQuery()
->select('id', 'code', 'name')
->from('products')
->where(['id', $productId])
->first();
if (!$product) {
return [
'success' => false,
'error' => 'Product not found'
];
}
// Generate barcode
$result = $this->barcodeManager->save($product->code, [
'height' => 60,
'fontSize' => 12
]);
if ($result['success']) {
// Update database
$this->db->createQuery()
->update('products')
->set([
'barcode_path' => $result['filepath'],
'barcode_generated_at' => date('Y-m-d H:i:s')
])
->where(['id', $productId])
->execute();
}
return $result;
}
/**
* Generate barcodes for all products without barcodes
*/
public function generateForAllProducts(): array
{
$products = $this->db->createQuery()
->select('id', 'code')
->from('products')
->where(['barcode_path', 'IS', null])
->toArray()
->execute();
$results = [
'total' => count($products),
'success' => 0,
'failed' => 0,
'details' => []
];
foreach ($products as $product) {
$result = $this->createForProduct($product['id']);
if ($result['success']) {
$results['success']++;
} else {
$results['failed']++;
}
$results['details'][$product['code']] = $result;
}
return $results;
}
/**
* Download barcode for product
*/
public function download(string $productCode): void
{
$barcode = Barcode::create($productCode, 60, 12);
$imageData = $barcode->toPng();
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="barcode_' . $productCode . '.png"');
header('Content-Length: ' . strlen($imageData));
echo $imageData;
}
}Best Practices
✅ DO:
// 1. Use try-catch for error handling
try {
$barcode = Barcode::create('CODE123', 60, 12);
$data = $barcode->toPng();
file_put_contents('barcode.png', $data);
} catch (Exception $e) {
error_log("Barcode error: " . $e->getMessage());
}
// 2. Check if image generated successfully
$imageData = $barcode->toPng();
if (strlen($imageData) > 0) {
file_put_contents('barcode.png', $imageData);
}
// 3. Use appropriate sizes
$barcode = Barcode::create('CODE', 60, 12); // Good - readable
// 4. Organize files systematically
$path = "barcodes/" . date('Y/m/') . $code . '.png';❌ DON'T:
// 1. Don't create barcodes that are too small
$barcode = Barcode::create('CODE', 10, 6); // Bad - hard to read
// 2. Don't forget to check if GD extension is installed
if (!extension_loaded('gd')) {
die('GD extension required');
}
// 3. Don't use non-existent fonts
$barcode->font = 'path/to/nonexistent/font.ttf'; // Will error
// 4. Don't create duplicate barcodes unnecessarily
// Check if file exists before creating new oneGotchas
1. Character Support
⚠️ Warning: Code 128 supports only specific characters and symbols
// ✅ Supported
$barcode = Barcode::create('ABC123');
$barcode = Barcode::create('Product-001');
$barcode = Barcode::create('SKU_2024_01');
// ❌ May have issues - special characters
$barcode = Barcode::create('สินค้า123'); // Thai - not supported
$barcode = Barcode::create('產品123'); // Chinese - not supported2. GD Extension
📋 Requirements: GD extension must be installed
// Check before use
if (!extension_loaded('gd')) {
throw new Exception('GD extension is required for barcode generation');
}3. Font File
ℹ️ Note: If fontSize > 0, font file must exist
// Check font file
$barcode = Barcode::create('CODE', 60, 12);
if (!file_exists($barcode->font)) {
// If no font, disable text display
$barcode = Barcode::create('CODE', 60, 0); // fontSize = 0
}4. Memory and Performance
// Creating many barcodes - do in batches
$codes = range(1, 10000); // 10,000 barcodes
// ✅ Good - process in batches
$batches = array_chunk($codes, 100);
foreach ($batches as $batch) {
foreach ($batch as $code) {
$barcode = Barcode::create($code);
file_put_contents("barcode_{$code}.png", $barcode->toPng());
}
// Clear memory
gc_collect_cycles();
}Common Mistakes
❌ Mistake: Calling toPng() with parameters
// ❌ Wrong - toPng() doesn't accept parameters
$barcode = Barcode::create('CODE');
$imageData = $barcode->toPng('CODE', 200, 80); // ERROR!
// ✅ Correct - set values at create()
$barcode = Barcode::create('CODE', 80, 14);
$imageData = $barcode->toPng();Fix: All parameters must be passed through create() only
❌ Mistake: Not checking if image generated successfully
// ❌ Bad
$imageData = $barcode->toPng();
file_put_contents('barcode.png', $imageData);
// ✅ Good
$imageData = $barcode->toPng();
if (strlen($imageData) > 0) {
$result = file_put_contents('barcode.png', $imageData);
if ($result === false) {
throw new Exception('Failed to save barcode');
}
}❌ Mistake: Using filenames with special characters
// ❌ May have issues
file_put_contents('barcode/product 001.png', $imageData);
// ✅ Good - use safe names
$filename = 'barcode_' . preg_replace('/[^a-zA-Z0-9_-]/', '_', $code) . '.png';
file_put_contents($filename, $imageData);FAQ (Frequently Asked Questions)
Q: Can I change barcode colors?
A: Not directly. The Barcode class creates black barcodes on white background only. For other colors, post-process the image.
Q: Does it support other barcode formats besides Code 128?
A: No, this class only supports Code 128.
Q: Can I display barcode directly in browser?
A: Yes, use header('Content-Type: image/png') and echo the image data.
Q: What's the recommended size for barcodes?
A: Recommended height is 60-80 pixels for general display, and fontSize 12-14 for text.
Related Classes
💡 Tip: For large systems, create a BarcodeManager class to centralize barcode management
⚠️ Important: Check that GD extension is installed before use
Setup
Required prerequisites or configuration before using this component.
Basic Usage
A minimal, runnable example with comments and expected output.
// Basic database usage (SQL generation safe)
$db = \Kotchasan\DB::create();
$user = $db->first('users', ['id' => 1]);
// Expected: object for user id 1 or nullExplanation:
- Create the DB instance
- Run a simple read operation
- The comment shows the expected result
Main Features
Key capabilities and common use cases.
- Simple DB usage patterns
- Safe parameter binding by default
- Works with QueryBuilder for complex cases
Advanced Examples
More complex usage patterns and composition with other components.
// Use QueryBuilder for complex queries
$db = \Kotchasan\Database::create();
$q = $db->select(['u.id', 'u.name'])->from('users u')
->where(['u.status', 1])
->orderBy('u.name');
$sql = $q->toSql();
// Expected: SELECT with WHERE and ORDER BYAPI Reference
Summary of important methods and parameters (see above for full details).
Gotchas / Common Mistakes
Common pitfalls and how to avoid them.
- Avoid passing user input into raw SQL
- Use parameter binding instead of concatenation
- Use Sql::column() when you need a column reference
Additional Resources
Related guides and references within this documentation set.