LayoutProbe.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace app\common\library\ps;
  3. /**
  4. * 从原稿图读取页面尺寸和底色,给还原排版用。
  5. */
  6. class LayoutProbe
  7. {
  8. /**
  9. * @param string $path 本地图片路径
  10. * @return array
  11. */
  12. public static function inspect($path)
  13. {
  14. $out = [
  15. 'width' => 0,
  16. 'height' => 0,
  17. 'background' => '#ffffff',
  18. 'ratio' => 297 / 210,
  19. ];
  20. if (!$path || !is_file($path)) {
  21. return $out;
  22. }
  23. $info = @getimagesize($path);
  24. if (!$info || empty($info[0]) || empty($info[1])) {
  25. return $out;
  26. }
  27. $out['width'] = (int)$info[0];
  28. $out['height'] = (int)$info[1];
  29. $out['ratio'] = $info[1] / $info[0];
  30. $bg = self::sampleBackground($path, $info);
  31. if ($bg) {
  32. $out['background'] = $bg;
  33. }
  34. return $out;
  35. }
  36. /**
  37. * 取四角浅色均值,避开油墨。
  38. * @param string $path
  39. * @param array $info
  40. * @return string
  41. */
  42. protected static function sampleBackground($path, array $info)
  43. {
  44. if (!function_exists('imagecreatefromstring')) {
  45. return '#ffffff';
  46. }
  47. $bin = @file_get_contents($path);
  48. if ($bin === false || $bin === '') {
  49. return '#ffffff';
  50. }
  51. $im = @imagecreatefromstring($bin);
  52. if (!$im) {
  53. return '#ffffff';
  54. }
  55. $w = imagesx($im);
  56. $h = imagesy($im);
  57. $points = [
  58. [4, 4], [$w - 5, 4], [4, $h - 5], [$w - 5, $h - 5],
  59. [(int)($w / 2), 4], [4, (int)($h / 2)],
  60. ];
  61. $rs = $gs = $bs = [];
  62. foreach ($points as $p) {
  63. $rgb = imagecolorat($im, max(0, $p[0]), max(0, $p[1]));
  64. $r = ($rgb >> 16) & 0xFF;
  65. $g = ($rgb >> 8) & 0xFF;
  66. $b = $rgb & 0xFF;
  67. if (($r + $g + $b) < 180) {
  68. continue;
  69. }
  70. $rs[] = $r;
  71. $gs[] = $g;
  72. $bs[] = $b;
  73. }
  74. imagedestroy($im);
  75. if (!$rs) {
  76. return '#ffffff';
  77. }
  78. $n = count($rs);
  79. return sprintf('#%02x%02x%02x', (int)round(array_sum($rs) / $n), (int)round(array_sum($gs) / $n), (int)round(array_sum($bs) / $n));
  80. }
  81. }