QrReader.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. final class QrReader
  3. {
  4. const SOURCE_TYPE_FILE = 'file';
  5. const SOURCE_TYPE_BLOB = 'blob';
  6. const SOURCE_TYPE_RESOURCE = 'resource';
  7. public $result;
  8. function __construct($imgsource, $sourcetype = QrReader::SOURCE_TYPE_FILE, $isUseImagickIfAvailable = true)
  9. {
  10. try {
  11. switch($sourcetype) {
  12. case QrReader::SOURCE_TYPE_FILE:
  13. if($isUseImagickIfAvailable && extension_loaded('imagick')) {
  14. $im = new Imagick();
  15. $im->readImage($imgsource);
  16. }else {
  17. $image = file_get_contents($imgsource);
  18. $im = imagecreatefromstring($image);
  19. }
  20. break;
  21. case QrReader::SOURCE_TYPE_BLOB:
  22. if($isUseImagickIfAvailable && extension_loaded('imagick')) {
  23. $im = new Imagick();
  24. $im->readimageblob($imgsource);
  25. }else {
  26. $im = imagecreatefromstring($imgsource);
  27. }
  28. break;
  29. case QrReader::SOURCE_TYPE_RESOURCE:
  30. $im = $imgsource;
  31. if($isUseImagickIfAvailable && extension_loaded('imagick')) {
  32. $isUseImagickIfAvailable = true;
  33. }else {
  34. $isUseImagickIfAvailable = false;
  35. }
  36. break;
  37. }
  38. if($isUseImagickIfAvailable && extension_loaded('imagick')) {
  39. $width = $im->getImageWidth();
  40. $height = $im->getImageHeight();
  41. $source = new \Zxing\IMagickLuminanceSource($im, $width, $height);
  42. }else {
  43. $width = imagesx($im);
  44. $height = imagesy($im);
  45. $source = new \Zxing\GDLuminanceSource($im, $width, $height);
  46. }
  47. $histo = new \Zxing\Common\HybridBinarizer($source);
  48. $bitmap = new \Zxing\BinaryBitmap($histo);
  49. $reader = new \Zxing\Qrcode\QRCodeReader();
  50. $this->result = $reader->decode($bitmap);
  51. }catch (\Zxing\NotFoundException $er){
  52. $this->result = false;
  53. }catch( \Zxing\FormatException $er){
  54. $this->result = false;
  55. }catch( \Zxing\ChecksumException $er){
  56. $this->result = false;
  57. }
  58. }
  59. public function text()
  60. {
  61. if(method_exists($this->result,'toString')) {
  62. return ($this->result->toString());
  63. }else{
  64. return $this->result;
  65. }
  66. }
  67. public function decode()
  68. {
  69. return $this->text();
  70. }
  71. }