source-class-Com.Tecnick.Barcode.Type

It appears that you are using AdBlocking software. The cost of running this website is covered by advertisements. If you like it please feel free to a small amount of money to secure the future of this website.
Overview

Classes

Exceptions

  1: <?php
  2: /**
  3:  * Type.php
  4:  *
  5:  * @since       2015-02-21
  6:  * @category    Library
  7:  * @package     Barcode
  8:  * @author      Nicola Asuni <info@tecnick.com>
  9:  * @copyright   2015-2016 Nicola Asuni - Tecnick.com LTD
 10:  * @license     http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
 11:  * @link        https://github.com/tecnickcom/tc-lib-barcode
 12:  *
 13:  * This file is part of tc-lib-barcode software library.
 14:  */
 15: 
 16: namespace Com\Tecnick\Barcode;
 17: 
 18: use \Com\Tecnick\Barcode\Exception as BarcodeException;
 19: use \Com\Tecnick\Color\Exception as ColorException;
 20: 
 21: /**
 22:  * Com\Tecnick\Barcode\Type
 23:  *
 24:  * Barcode Type class
 25:  *
 26:  * @since       2015-02-21
 27:  * @category    Library
 28:  * @package     Barcode
 29:  * @author      Nicola Asuni <info@tecnick.com>
 30:  * @copyright   2015-2016 Nicola Asuni - Tecnick.com LTD
 31:  * @license     http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
 32:  * @link        https://github.com/tecnickcom/tc-lib-barcode
 33:  */
 34: abstract class Type extends \Com\Tecnick\Barcode\Type\Convert
 35: {
 36:     /**
 37:      * Barcode type (linear or square)
 38:      *
 39:      * @var string
 40:      */
 41:     protected $type = '';
 42: 
 43:     /**
 44:      * Barcode format
 45:      *
 46:      * @var string
 47:      */
 48:     protected $format = '';
 49:     
 50:     /**
 51:      * Array containing extra parameters for the specified barcode type
 52:      *
 53:      * @var array
 54:      */
 55:     protected $params;
 56: 
 57:     /**
 58:      * Code to convert (barcode content)
 59:      *
 60:      * @var string
 61:      */
 62:     protected $code = '';
 63: 
 64:     /**
 65:      * Resulting code after applying checksum etc.
 66:      *
 67:      * @var string
 68:      */
 69:     protected $extcode = '';
 70: 
 71:     /**
 72:      * Total number of columns
 73:      *
 74:      * @var int
 75:      */
 76:     protected $ncols = 0;
 77: 
 78:     /**
 79:      * Total number of rows
 80:      *
 81:      * @var int
 82:      */
 83:     protected $nrows = 1;
 84: 
 85:     /**
 86:      * Array containing the position and dimensions of each barcode bar
 87:      * (x, y, width, height)
 88:      *
 89:      * @var array
 90:      */
 91:     protected $bars = array();
 92: 
 93:     /**
 94:      * Barcode width
 95:      *
 96:      * @var float
 97:      */
 98:     protected $width;
 99:     
100:     /**
101:      * Barcode height
102:      *
103:      * @var float
104:      */
105:     protected $height;
106: 
107:     /**
108:      * Additional padding to add around the barcode (top, right, bottom, left) in user units.
109:      * A negative value indicates the multiplication factor for each row or column.
110:      *
111:      * @var array
112:      */
113:     protected $padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
114: 
115:     /**
116:      * Ratio between the barcode width and the number of rows
117:      *
118:      * @var float
119:      */
120:     protected $width_ratio;
121: 
122:     /**
123:      * Ratio between the barcode height and the number of columns
124:      *
125:      * @var float
126:      */
127:     protected $height_ratio;
128: 
129:     /**
130:      * Foreground Color object
131:      *
132:      * @var Color object
133:      */
134:     protected $color_obj;
135: 
136:     /**
137:      * Backgorund Color object
138:      *
139:      * @var Color object
140:      */
141:     protected $bg_color_obj;
142: 
143:     /**
144:      * Initialize a new barcode object
145:      *
146:      * @param string $code    Barcode content
147:      * @param int    $width   Barcode width in user units (excluding padding).
148:      *                        A negative value indicates the multiplication factor for each column.
149:      * @param int    $height  Barcode height in user units (excluding padding).
150:      *                        A negative value indicates the multiplication factor for each row.
151:      * @param string $color   Foreground color in Web notation (color name, or hexadecimal code, or CSS syntax)
152:      * @param array  $params  Array containing extra parameters for the specified barcode type
153:      * @param array  $padding Additional padding to add around the barcode (top, right, bottom, left) in user units.
154:      *                        A negative value indicates the number or rows or columns.
155:      *
156:      * @throws BarcodeException in case of error
157:      * @throws ColorException in case of color error
158:      */
159:     public function __construct(
160:         $code,
161:         $width = -1,
162:         $height = -1,
163:         $color = 'black',
164:         $params = array(),
165:         $padding = array(0, 0, 0, 0)
166:     ) {
167:         $this->code = $code;
168:         $this->extcode = $code;
169:         $this->params = $params;
170:         $this->setParameters();
171:         $this->setBars();
172:         $this->setSize($width, $height, $padding);
173:         $this->setColor($color);
174:     }
175: 
176:     /**
177:      * Set extra (optional) parameters
178:      */
179:     protected function setParameters()
180:     {
181:     }
182: 
183:     /**
184:      * Set the bars array
185:      *
186:      * @throws BarcodeException in case of error
187:      */
188:     abstract protected function setBars();
189: 
190:     /**
191:      * Set the size of the barcode to be exported
192:      *
193:      * @param int    $width   Barcode width in user units (excluding padding).
194:      *                        A negative value indicates the multiplication factor for each column.
195:      * @param int    $height  Barcode height in user units (excluding padding).
196:      *                        A negative value indicates the multiplication factor for each row.
197:      * @param array  $padding Additional padding to add around the barcode (top, right, bottom, left) in user units.
198:      *                        A negative value indicates the number or rows or columns.
199:      */
200:     public function setSize($width, $height, $padding = array(0, 0, 0, 0))
201:     {
202:         $this->width = intval($width);
203:         if ($this->width <= 0) {
204:             $this->width = (abs(min(-1, $this->width)) * $this->ncols);
205:         }
206: 
207:         $this->height = intval($height);
208:         if ($this->height <= 0) {
209:             $this->height = (abs(min(-1, $this->height)) * $this->nrows);
210:         }
211: 
212:         $this->width_ratio = ($this->width / $this->ncols);
213:         $this->height_ratio = ($this->height / $this->nrows);
214: 
215:         $this->setPadding($padding);
216: 
217:         return $this;
218:     }
219: 
220:     /**
221:      * Set the barcode padding
222:      *
223:      * @param array  $padding Additional padding to add around the barcode (top, right, bottom, left) in user units.
224:      *                        A negative value indicates the number or rows or columns.
225:      *
226:      * @throws BarcodeException in case of error
227:      */
228:     protected function setPadding($padding)
229:     {
230:         if (!is_array($padding) || (count($padding) != 4)) {
231:             throw new BarcodeException('Invalid padding, expecting an array of 4 numbers (top, right, bottom, left)');
232:         }
233:         $map = array(
234:             array('T', $this->height_ratio),
235:             array('R', $this->width_ratio),
236:             array('B', $this->height_ratio),
237:             array('L', $this->width_ratio)
238:         );
239:         foreach ($padding as $key => $val) {
240:             $val = intval($val);
241:             if ($val < 0) {
242:                 $val = (abs(min(-1, $val)) * $map[$key][1]);
243:             }
244:             $this->padding[$map[$key][0]] = $val;
245:         }
246: 
247:         return $this;
248:     }
249: 
250:     /**
251:      * Set the color of the bars.
252:      * If the color is transparent or empty it will be set to the default black color.
253:      *
254:      * @param string $color Foreground color in Web notation (color name, or hexadecimal code, or CSS syntax)
255:      *
256:      * @throws ColorException in case of color error
257:      * @throws BarcodeException in case of empty or transparent color
258:      */
259:     public function setColor($color)
260:     {
261:         $this->color_obj = $this->getRgbColorObject($color);
262:         if ($this->color_obj === null) {
263:             throw new BarcodeException('The foreground color cannot be empty or transparent');
264:         }
265:         return $this;
266:     }
267: 
268:     /**
269:      * Set the background color
270:      *
271:      * @param string $color Background color in Web notation (color name, or hexadecimal code, or CSS syntax)
272:      *
273:      * @throws ColorException in case of color error
274:      */
275:     public function setBackgroundColor($color)
276:     {
277:         $this->bg_color_obj = $this->getRgbColorObject($color);
278:         return $this;
279:     }
280: 
281:     /**
282:      * Get the RGB Color object for the given color representation
283:      *
284:      * @param string $color Color in Web notation (color name, or hexadecimal code, or CSS syntax)
285:      *
286:      * @return Color object or null
287:      *
288:      * @throws ColorException in case of color error
289:      */
290:     protected function getRgbColorObject($color)
291:     {
292:         $conv = new \Com\Tecnick\Color\Pdf();
293:         $cobj = $conv->getColorObject($color);
294:         if ($cobj !== null) {
295:             return new \Com\Tecnick\Color\Model\Rgb($cobj->toRgbArray());
296:         }
297:         return null;
298:     }
299: 
300:     /**
301:      * Get the barcode raw array
302:      *
303:      * @return array
304:      */
305:     public function getArray()
306:     {
307:         return array(
308:             'type'         => $this->type,
309:             'format'       => $this->format,
310:             'params'       => $this->params,
311:             'code'         => $this->code,
312:             'extcode'      => $this->extcode,
313:             'ncols'        => $this->ncols,
314:             'nrows'        => $this->nrows,
315:             'width'        => $this->width,
316:             'height'       => $this->height,
317:             'width_ratio'  => $this->width_ratio,
318:             'height_ratio' => $this->height_ratio,
319:             'padding'      => $this->padding,
320:             'full_width'   => ($this->width + $this->padding['L'] + $this->padding['R']),
321:             'full_height'  => ($this->height + $this->padding['T'] + $this->padding['B']),
322:             'color_obj'    => $this->color_obj,
323:             'bg_color_obj' => $this->bg_color_obj,
324:             'bars'         => $this->bars
325:         );
326:     }
327: 
328:     /**
329:      * Get the extended code (code + checksum)
330:      *
331:      * @return string
332:      */
333:     public function getExtendedCode()
334:     {
335:         return $this->extcode;
336:     }
337: 
338:     /**
339:      * Get the barcode as SVG image object
340:      */
341:     public function getSvg()
342:     {
343:         $data = $this->getSvgCode();
344:         header('Content-Type: application/svg+xml');
345:         header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
346:         header('Pragma: public');
347:         header('Expires: Thu, 04 jan 1973 00:00:00 GMT'); // Date in the past
348:         header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
349:         header('Content-Disposition: inline; filename="'.md5($data).'.svg";');
350:         if (empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
351:             // the content length may vary if the server is using compression
352:             header('Content-Length: '.strlen($data));
353:         }
354:         echo $data;
355:     }
356: 
357:     /**
358:      * Get the barcode as SVG code
359:      *
360:      * @return string SVG code
361:      */
362:     public function getSvgCode()
363:     {
364:         // flags for htmlspecialchars
365:         $hflag = ENT_NOQUOTES;
366:         if (defined('ENT_XML1')) {
367:             $hflag = ENT_XML1;
368:         }
369:         $width = sprintf('%F', ($this->width + $this->padding['L'] + $this->padding['R']));
370:         $height = sprintf('%F', ($this->height + $this->padding['T'] + $this->padding['B']));
371:         $svg = '<?xml version="1.0" standalone="no" ?>'."\n"
372:             .'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'."\n"
373:             .'<svg'
374:             .' width="'.$width.'"'
375:             .' height="'.$height.'"'
376:             .' viewBox="0 0 '.$width.' '.$height.'"'
377:             .' version="1.1"'
378:             .' xmlns="http://www.w3.org/2000/svg"'
379:             .'>'."\n"
380:             ."\t".'<desc>'.htmlspecialchars($this->code, $hflag, 'UTF-8').'</desc>'."\n";
381:         if ($this->bg_color_obj !== null) {
382:             $svg .= "\t".'<rect'
383:                 .' x="0"'
384:                 .' y="0"'
385:                 .' width="'.$width.'"'
386:                 .' height="'.$height.'"'
387:                 .' fill="'.$this->bg_color_obj->getRgbHexColor().'"'
388:                 .' stroke="none"'
389:                 .' stroke-width="0"'
390:                 .' stroke-linecap="square"'
391:                 .' />'."\n";
392:         }
393:         $svg .= "\t".'<g'
394:             .' id="bars"'
395:             .' fill="'.$this->color_obj->getRgbHexColor().'"'
396:             .' stroke="none"'
397:             .' stroke-width="0"'
398:             .' stroke-linecap="square"'
399:             .'>'."\n";
400:         $bars = $this->getBarsArray('XYWH');
401:         foreach ($bars as $rect) {
402:             $svg .= "\t\t".'<rect'
403:                 .' x="'.sprintf('%F', $rect[0]).'"'
404:                 .' y="'.sprintf('%F', $rect[1]).'"'
405:                 .' width="'.sprintf('%F', $rect[2]).'"'
406:                 .' height="'.sprintf('%F', $rect[3]).'"'
407:                 .' />'."\n";
408:         }
409:         $svg .= "\t".'</g>'."\n"
410:             .'</svg>'."\n";
411:         return $svg;
412:     }
413: 
414:     /**
415:      * Get an HTML representation of the barcode.
416:      *
417:      * @return string HTML code (DIV block)
418:      */
419:     public function getHtmlDiv()
420:     {
421:         $html = '<div style="'
422:             .'width:'.sprintf('%F', ($this->width + $this->padding['L'] + $this->padding['R'])).'px;'
423:             .'height:'.sprintf('%F', ($this->height + $this->padding['T'] + $this->padding['B'])).'px;'
424:             .'position:relative;'
425:             .'font-size:0;'
426:             .'border:none;'
427:             .'padding:0;'
428:             .'margin:0;';
429:         if ($this->bg_color_obj !== null) {
430:             $html .= 'background-color:'.$this->bg_color_obj->getCssColor().';';
431:         }
432:         $html .= '">'."\n";
433:         $bars = $this->getBarsArray('XYWH');
434:         foreach ($bars as $rect) {
435:             $html .= "\t".'<div style="background-color:'.$this->color_obj->getCssColor().';'
436:                 .'left:'.sprintf('%F', $rect[0]).'px;'
437:                 .'top:'.sprintf('%F', $rect[1]).'px;'
438:                 .'width:'.sprintf('%F', $rect[2]).'px;'
439:                 .'height:'.sprintf('%F', $rect[3]).'px;'
440:                 .'position:absolute;'
441:                 .'border:none;'
442:                 .'padding:0;'
443:                 .'margin:0;'
444:                 .'">&nbsp;</div>'."\n";
445:         }
446:         $html .= '</div>'."\n";
447:         return $html;
448:     }
449: 
450:     /**
451:      * Get Barcode as PNG Image (requires GD or Imagick library)
452:      */
453:     public function getPng()
454:     {
455:         $data = $this->getPngData();
456:         header('Content-Type: image/png');
457:         header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
458:         header('Pragma: public');
459:         header('Expires: Thu, 04 jan 1973 00:00:00 GMT'); // Date in the past
460:         header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
461:         header('Content-Disposition: inline; filename="'.md5($data).'.png";');
462:         if (empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
463:             // the content length may vary if the server is using compression
464:             header('Content-Length: '.strlen($data));
465:         }
466:         echo $data;
467:     }
468: 
469:     /**
470:      * Get the barcode as PNG image (requires GD or Imagick library)
471:      *
472:      * @param bool $imagick If true try to use the Imagick extension
473:      *
474:      * @return string PNG image data
475:      */
476:     public function getPngData($imagick = true)
477:     {
478:         if ($imagick && extension_loaded('imagick')) {
479:             return $this->getPngDataImagick();
480:         }
481:         $img = $this->getGd();
482:         ob_start();
483:         imagepng($img);
484:         return ob_get_clean();
485:     }
486: 
487:     /**
488:      * Get the barcode as PNG image (requires Imagick library)
489:      *
490:      * @return object
491:      *
492:      * @throws BarcodeException if the Imagick library is not installed
493:      */
494:     public function getPngDataImagick()
495:     {
496:         $img = new \Imagick();
497:         $width = ceil($this->width + $this->padding['L'] + $this->padding['R']);
498:         $height = ceil($this->height + $this->padding['T'] + $this->padding['B']);
499:         $img->newImage($width, $height, 'none', 'png');
500:         $barcode = new \imagickdraw();
501:         if ($this->bg_color_obj !== null) {
502:             $rgbcolor = $this->bg_color_obj->getNormalizedArray(255);
503:             $bg_color = new \imagickpixel('rgb('.$rgbcolor['R'].','.$rgbcolor['G'].','.$rgbcolor['B'].')');
504:             $barcode->setfillcolor($bg_color);
505:             $barcode->rectangle(0, 0, $width, $height);
506:         }
507:         $rgbcolor = $this->color_obj->getNormalizedArray(255);
508:         $bar_color = new \imagickpixel('rgb('.$rgbcolor['R'].','.$rgbcolor['G'].','.$rgbcolor['B'].')');
509:         $barcode->setfillcolor($bar_color);
510:         $bars = $this->getBarsArray('XYXY');
511:         foreach ($bars as $rect) {
512:             $barcode->rectangle($rect[0], $rect[1], $rect[2], $rect[3]);
513:         }
514:         $img->drawimage($barcode);
515:         return $img->getImageBlob();
516:     }
517: 
518:     /**
519:      * Get the barcode as GD image object (requires GD library)
520:      *
521:      * @return object
522:      *
523:      * @throws BarcodeException if the GD library is not installed
524:      */
525:     public function getGd()
526:     {
527:         $width = ceil($this->width + $this->padding['L'] + $this->padding['R']);
528:         $height = ceil($this->height + $this->padding['T'] + $this->padding['B']);
529:         $img = imagecreate($width, $height);
530:         if ($this->bg_color_obj === null) {
531:             $bgobj = clone $this->color_obj;
532:             $rgbcolor = $bgobj->invertColor()->getNormalizedArray(255);
533:             $background_color = imagecolorallocate($img, $rgbcolor['R'], $rgbcolor['G'], $rgbcolor['B']);
534:             imagecolortransparent($img, $background_color);
535:         } else {
536:             $rgbcolor = $this->bg_color_obj->getNormalizedArray(255);
537:             $bg_color = imagecolorallocate($img, $rgbcolor['R'], $rgbcolor['G'], $rgbcolor['B']);
538:             imagefilledrectangle($img, 0, 0, $width, $height, $bg_color);
539:         }
540:         $rgbcolor = $this->color_obj->getNormalizedArray(255);
541:         $bar_color = imagecolorallocate($img, $rgbcolor['R'], $rgbcolor['G'], $rgbcolor['B']);
542:         $bars = $this->getBarsArray('XYXY');
543:         foreach ($bars as $rect) {
544:             imagefilledrectangle($img, $rect[0], $rect[1], $rect[2], $rect[3], $bar_color);
545:         }
546:         return $img;
547:     }
548: 
549:     /**
550:      * Get a raw barcode string representation using characters
551:      *
552:      * @param string $space_char Character or string to use for filling empty spaces
553:      * @param string $bar_char   Character or string to use for filling bars
554:      *
555:      * @return string
556:      */
557:     public function getGrid($space_char = '0', $bar_char = '1')
558:     {
559:         $raw = $this->getGridArray($space_char, $bar_char);
560:         $grid = '';
561:         foreach ($raw as $row) {
562:             $grid .= implode($row)."\n";
563:         }
564:         return $grid;
565:     }
566: 
567:     /**
568:      * Get the array containing all the formatted bars coordinates
569:      *
570:      * @param string $type Type of coordinates to return: 'XYXY' or 'XYWH'
571:      *
572:      * @return array
573:      */
574:     public function getBarsArray($type = 'XYXY')
575:     {
576:         $mtd = 'getBarRect'.$type;
577:         $rect = array();
578:         foreach ($this->bars as $bar) {
579:             if (($bar[2] > 0) && ($bar[3] > 0)) {
580:                 $rect[] = $this->$mtd($bar);
581:             }
582:         }
583:         if ($this->nrows > 1) {
584:             // reprint rotated to cancel row gaps
585:             $rot = $this->getRotatedBarArray();
586:             foreach ($rot as $bar) {
587:                 if (($bar[2] > 0) && ($bar[3] > 0)) {
588:                     $rect[] = $this->$mtd($bar);
589:                 }
590:             }
591:         }
592:         return $rect;
593:     }
594: }
595: 
 

© 2004-2017 – Nicola Asuni - Tecnick.com - All rights reserved.
about - disclaimer - privacy