文章详情
php处理图片均匀化图像亮度
Posted on 2024-09-11 02:42:23 by 主打一个C++
要实现图片亮度均匀化,主要思路是与C++同样,遍历每个像素,计算其亮度,然后根据需要调整亮度值,使其趋于固定的值。
//示例,小小封装一个函数:
function f_adjustBrightness($imagePath, $targetBrightness, $outputPath) {
// 加载图像
$image = imagecreatefrompng($imagePath);
if (!$image) {
die("无法加载图像!");
}
// 获取图像尺寸
$width = imagesx($image);
$height = imagesy($image);
// 遍历每个像素,调整亮度
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
// 计算当前亮度
$currentBrightness = ($r + $g + $b) / 3;
// 计算亮度调整差
$brightnessDifference = $targetBrightness - $currentBrightness;
// 调整RGB值
$newR = min(max($r + $brightnessDifference, 0), 255);
$newG = min(max($g + $brightnessDifference, 0), 255);
$newB = min(max($b + $brightnessDifference, 0), 255);
// 设置新的颜色
$newColor = imagecolorallocate($image, $newR, $newG, $newB);
imagesetpixel($image, $x, $y, $newColor);
}
}
// 保存调整后的图像
imagejpeg($image, $outputPath);
// 释放内存
imagedestroy($image);
echo "图像亮度均匀化完成,已保存至:$outputPath\n";
}
//调用
$sourceImage = __DIR__ . '/test.png';
$targetBrightness = 128; // 目标亮度值
$outputImage = __DIR__ . '/output.png';
f_adjustBrightness($sourceImage, $targetBrightness, $outputImage);
//处理前
处理后
*转载请注明出处:原文链接:https://cpp.vin/page/32.html