BCGDrawJPG.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. /**
  3. *--------------------------------------------------------------------
  4. *
  5. * Image Class to draw JPG images with possibility to set DPI
  6. *
  7. *--------------------------------------------------------------------
  8. * Copyright (C) Jean-Sebastien Goupil
  9. * http://www.barcodephp.com
  10. */
  11. include_once('BCGDraw.php');
  12. if (!function_exists('file_put_contents')) {
  13. function file_put_contents($filename, $data) {
  14. $f = @fopen($filename, 'w');
  15. if (!$f) {
  16. return false;
  17. } else {
  18. $bytes = fwrite($f, $data);
  19. fclose($f);
  20. return $bytes;
  21. }
  22. }
  23. }
  24. class BCGDrawJPG extends BCGDraw {
  25. private $dpi;
  26. private $quality;
  27. /**
  28. * Constructor.
  29. *
  30. * @param resource $im
  31. */
  32. public function __construct($im) {
  33. parent::__construct($im);
  34. }
  35. /**
  36. * Sets the DPI.
  37. *
  38. * @param int $dpi
  39. */
  40. public function setDPI($dpi) {
  41. if(is_int($dpi)) {
  42. $this->dpi = max(1, $dpi);
  43. } else {
  44. $this->dpi = null;
  45. }
  46. }
  47. /**
  48. * Sets the quality of the JPG.
  49. *
  50. * @param int $quality
  51. */
  52. public function setQuality($quality) {
  53. $this->quality = $quality;
  54. }
  55. /**
  56. * Draws the JPG on the screen or in a file.
  57. */
  58. public function draw() {
  59. ob_start();
  60. imagejpeg($this->im, null, $this->quality);
  61. $bin = ob_get_contents();
  62. ob_end_clean();
  63. $this->setInternalProperties($bin);
  64. if (empty($this->filename)) {
  65. echo $bin;
  66. } else {
  67. file_put_contents($this->filename, $bin);
  68. }
  69. }
  70. private function setInternalProperties(&$bin) {
  71. $this->internalSetDPI($bin);
  72. $this->internalSetC($bin);
  73. }
  74. private function internalSetDPI(&$bin) {
  75. if ($this->dpi !== null) {
  76. $bin = substr_replace($bin, pack("Cnn", 0x01, $this->dpi, $this->dpi), 13, 5);
  77. }
  78. }
  79. private function internalSetC(&$bin) {
  80. if(strcmp(substr($bin, 0, 4), pack('H*', 'FFD8FFE0')) === 0) {
  81. $offset = 4 + (ord($bin[4]) << 8 | ord($bin[5]));
  82. $firstPart = substr($bin, 0, $offset);
  83. $secondPart = substr($bin, $offset);
  84. $cr = pack('H*', 'FFFE004447656E657261746564207769746820426172636F64652047656E657261746F7220666F722050485020687474703A2F2F7777772E626172636F64657068702E636F6D');
  85. $bin = $firstPart;
  86. $bin .= $cr;
  87. $bin .= $secondPart;
  88. }
  89. }
  90. }
  91. ?>