diff --git a/res.jpg b/res.jpg index 6c8d324..6aea73c 100644 Binary files a/res.jpg and b/res.jpg differ diff --git a/src/IdPhotoBackgroundSwitch/IdPhotoHelper.php b/src/IdPhotoBackgroundSwitch/IdPhotoHelper.php index 0828432..4631a79 100644 --- a/src/IdPhotoBackgroundSwitch/IdPhotoHelper.php +++ b/src/IdPhotoBackgroundSwitch/IdPhotoHelper.php @@ -10,10 +10,22 @@ class IdPhotoHelper static $ignore_piexl = 0.01; //像素横向左右存在该比例无需替换颜色的像素时,无效该像素替换 static $distinct_piexl = 80; //rgb像素整体偏差范围 - public static function transformImage(string $from_image_path, string $to_image_path, array $color = self::RED_COLOR) + /** + * 证件照背景颜色替换 + * @param string $from_image_path //来源图片路径 + * @param string $to_image_path //目标图片路径 + * @param array|int[] $color //rgb颜色,示例:[255,0,0] + * @param array $return_size // 宽高,示例:[400,300] + * @author 我只想看看蓝天 <1207032539@qq.com> + */ + public static function transformImage(string $from_image_path, string $to_image_path, array $color = self::RED_COLOR, array $return_size = []) { $old_image = imagecreatefromstring(file_get_contents($from_image_path)); - list($old_image_width, $old_image_height) = getimagesize($from_image_path);//获取长和宽 + if (!empty($return_size)) { + $old_image = self::resetImage($old_image, $return_size); + } + $old_image_width = imagesx($old_image);//获取长和宽 + $old_image_height = imagesy($old_image); $new = imagecreatetruecolor($old_image_width, $old_image_height);//创建一个背景图 $color = imagecolorallocate($new, $color[0] ?? 0, $color[1] ?? 0, $color[2] ?? 0); imagefill($new, 0, 0, $color); @@ -98,4 +110,24 @@ private static function collectBackgroupColor($image) $b = $rgb & 0xff;//取B return [$r, $g, $b]; } + + /** + * 重置图片(可实现低损压缩) + * @param $image + * @param array $return_size //示例:[400,300] 宽高 + * @return false|\GdImage|resource + * @author 我只想看看蓝天 <1207032539@qq.com> + */ + private static function resetImage($image, $return_size = []) + { + $width = imagesx($image); //获取原图尺寸 + $height = imagesy($image); //获取原图尺寸 + //缩放尺寸 + $new_width = $return_size[0] ?? $width; + $new_height = $return_size[1] ?? $height; + $dst_image = imagecreatetruecolor($new_width, $new_height); + imagecopyresized($dst_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); + imagedestroy($image); + return $dst_image; + } } diff --git a/tests/Test.php b/tests/Test.php index bb375b1..a01c6d9 100644 --- a/tests/Test.php +++ b/tests/Test.php @@ -15,6 +15,6 @@ class Test extends TestCase { public function testIdPhotoHelper() { - IdPhotoHelper::transformImage('test.jpg', 'res.jpg'); + IdPhotoHelper::transformImage('test.jpg', 'res.jpg', IdPhotoHelper::WHITE_COLOR, [413, 295]); } }