PHP基于原生GD库, 获取图片中文字颜色, 匹配稀有度
一,获取文字颜色部分
如果背景有渐变色就不是很准, 如果对颜色没有特殊要求,建议使用调整图片对比度
二, 匹配对应的稀有度数据
这块不是很重要根据自己情况调整文章来源:https://uudwc.com/A/AAkYq
/**
* 根据文字颜色获取稀有度
* @param Request $request
* @return mixed|void|null
*/
public function getTextColor(Request $request)
{
// 获得图片文件
$file = $request->file('img');
// 文件扩展
$extension = $file->extension();
// 文件尺寸信息(width, height)
$imageSize = getimagesize($file);
// 图片格式不同,需要调用不同的函数
$image = null;
if ($extension === 'png') {
$image = imagecreatefrompng($file);
}
if ($extension === 'webp') {
$image = imagecreatefromwebp($file);
}
if ($extension === 'jpg' || $extension === 'jpeg') {
$image = imagecreatefromjpeg($file);
}
// 都没有匹配到返回提示信息
if (is_null($image)) {
exit(json_encode(['code' => 400, 'message' => '未知图片格式']));
}
// 调整对比度(重要)
imagefilter($image, IMG_FILTER_CONTRAST, -50);
// 文字颜色
$result = $this->getTextColors($image, $imageSize[0], $imageSize[1]);
// 稀有度
return $this->getRarity($result);
}
/**
* 获取文字颜色
* @param $image
* @param $imageWidth
* @param $imageHeight
* @return mixed
*/
public function getTextColors($image, $imageWidth, $imageHeight)
{
// 假设图像中文字区域的左上角坐标为(100, 100),宽度为200,高度为50
$textRegionX = 0;
$textRegionY = 0;
$textRegionWidth = $imageWidth;
$textRegionHeight = $imageHeight;
// 数组用于存储颜色及其数量
$colors = array();
// 循环遍历文字区域内的像素
for ($x = $textRegionX; $x < $textRegionX + $textRegionWidth; $x++) {
for ($y = $textRegionY; $y < $textRegionY + $textRegionHeight; $y++) {
// 获取像素的颜色
$color = @imagecolorat($image, $x, $y);
// 将颜色转换为RGB值
$rgb = imagecolorsforindex($image, $color);
// 将颜色添加到数组中
$colors[$color] = isset($colors[$color]) ? $colors[$color] + 1 : 1;
}
}
// 根据颜色数量排序数组
arsort($colors);
// 获取前两种颜色
$topColors = array_slice($colors, 0, 2, true);
$colorArr = [];
// 输出前两种颜色
foreach ($topColors as $color => $count) {
$rgb = imagecolorsforindex($image, $color);
array_push($colorArr, "RGB({$rgb['red']},{$rgb['green']},{$rgb['blue']})");
}
return $colorArr[1];
}
/**
* 获取稀有度
* @param string $rgb
* @return mixed|null
*/
public function getRarity(string $rgb)
{
// 定义颜色的RGB范围
$colors = [
[
'color' => '灰色',
'rarity' => '粗糙',
'rgb' => 'RGB(146,146,146)',
],
[
'color' => '白色',
'rarity' => '普通',
'rgb' => 'RGB(255,255,255)',
],
[
'color' => '绿色',
'rarity' => '优秀',
'rgb' => 'RGB(160,255,0)',
],
[
'color' => '蓝色',
'rarity' => '稀有',
'rgb' => 'RGB(0,171,255)',
],
[
'color' => '紫色',
'rarity' => '史诗',
'rgb' => 'RGB(255,72,255)',
],
[
'color' => '橙色',
'rarity' => '传说',
'rgb' => 'RGB(255,196,0)',
],
[
'color' => '黄色',
'rarity' => '暗金',
'rgb' => 'RGB(255,255,187)',
],
];
// 查找rgb相等的
$result = collect($colors)->filter(function ($item) use ($rgb) {
return $item['rgb'] === $rgb;
})->values()->all();
// 如果没有匹配到返回null
if (empty($result)) {
return null;
}
return array_values($result)[0];
}
有部分代码是使用
Laravel
框架的集合完成的
主要分为两部分文章来源地址https://uudwc.com/A/AAkYq