Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
luler committed Jun 25, 2021
1 parent 5d09dbc commit 8c2cd4a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
Binary file modified res.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 34 additions & 2 deletions src/IdPhotoBackgroundSwitch/IdPhotoHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}
}
2 changes: 1 addition & 1 deletion tests/Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
}

0 comments on commit 8c2cd4a

Please sign in to comment.