| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace app\common\library\ps;
- /**
- * 从原稿图读取页面尺寸和底色,给还原排版用。
- */
- class LayoutProbe
- {
- /**
- * @param string $path 本地图片路径
- * @return array
- */
- public static function inspect($path)
- {
- $out = [
- 'width' => 0,
- 'height' => 0,
- 'background' => '#ffffff',
- 'ratio' => 297 / 210,
- ];
- if (!$path || !is_file($path)) {
- return $out;
- }
- $info = @getimagesize($path);
- if (!$info || empty($info[0]) || empty($info[1])) {
- return $out;
- }
- $out['width'] = (int)$info[0];
- $out['height'] = (int)$info[1];
- $out['ratio'] = $info[1] / $info[0];
- $bg = self::sampleBackground($path, $info);
- if ($bg) {
- $out['background'] = $bg;
- }
- return $out;
- }
- /**
- * 取四角浅色均值,避开油墨。
- * @param string $path
- * @param array $info
- * @return string
- */
- protected static function sampleBackground($path, array $info)
- {
- if (!function_exists('imagecreatefromstring')) {
- return '#ffffff';
- }
- $bin = @file_get_contents($path);
- if ($bin === false || $bin === '') {
- return '#ffffff';
- }
- $im = @imagecreatefromstring($bin);
- if (!$im) {
- return '#ffffff';
- }
- $w = imagesx($im);
- $h = imagesy($im);
- $points = [
- [4, 4], [$w - 5, 4], [4, $h - 5], [$w - 5, $h - 5],
- [(int)($w / 2), 4], [4, (int)($h / 2)],
- ];
- $rs = $gs = $bs = [];
- foreach ($points as $p) {
- $rgb = imagecolorat($im, max(0, $p[0]), max(0, $p[1]));
- $r = ($rgb >> 16) & 0xFF;
- $g = ($rgb >> 8) & 0xFF;
- $b = $rgb & 0xFF;
- if (($r + $g + $b) < 180) {
- continue;
- }
- $rs[] = $r;
- $gs[] = $g;
- $bs[] = $b;
- }
- imagedestroy($im);
- if (!$rs) {
- return '#ffffff';
- }
- $n = count($rs);
- return sprintf('#%02x%02x%02x', (int)round(array_sum($rs) / $n), (int)round(array_sum($gs) / $n), (int)round(array_sum($bs) / $n));
- }
- }
|