/** * This function will read an image with a Code 39 Barcode and will decode it. * * @access public * @static * @param IO\File $file the image's URI * @return string the decode value */ public static function decode(IO\File $file) { $image = NULL; $ext = $file->getFileExtension(); switch ($ext) { case 'png': $image = imagecreatefrompng($file); break; case 'jpg': $image = imagecreatefromjpeg($file); break; default: throw new Throwable\InvalidArgument\Exception('Unrecognized file format. File name must have either a png or jpg extension.', array('file' => $file)); } $width = imagesx($image); $height = imagesy($image); $y = floor($height / 2); // finds middle $pixels = array(); for ($x = 0; $x < $width; $x++) { $rgb = imagecolorat($image, $x, $y); $r = $rgb >> 16 & 0xff; $g = $rgb >> 8 & 0xff; $b = $rgb & 0xff; $pixels[$x] = ($r + $g + $b) / 3 < 128.0 ? 1 : 0; } $code = array(); $bw = array(); $i = 0; $code[0] = 1; $bw[0] = 'b'; for ($x = 1; $x < $width; $x++) { if ($pixels[$x] == $pixels[$x - 1]) { $code[$i]++; } else { $code[++$i] = 1; $bw[$i] = $pixels[$x] == 1 ? 'b' : 'w'; } } $max = 0; for ($x = 1; $x < count($code) - 1; $x++) { if ($code[$x] > $max) { $max = $code[$x]; } } $code_string = ''; for ($x = 1; $x < count($code) - 1; $x++) { $code_string .= $code[$x] > $max / 2 * 1.5 ? strtoupper($bw[$x]) : $bw[$x]; } // parse code string $msg = ''; for ($x = 0; $x < strlen($code_string); $x += 10) { $msg .= self::$patterns[substr($code_string, $x, 9)]; } return $msg; }