如何检测 PNG 图像是浅色还是深色

问题描述 投票:0回答:1

我一直在寻找一种解决方案来检测 PNG 图像的主要亮度是亮还是暗。这个概念是为所有 PNG 图像添加背景,但如果它太亮,则添加深色背景

我通过搜索找到了一些解决方案,但似乎它们不适用于透明背景图像。你能给我一些想法吗?

php image colors imagemagick png
1个回答
0
投票

很有趣。 你能试试这个吗?告诉我这适合你吗?

// Load the image using ImageMagick
$image = new \Imagick('path/to/image.png');

// Get the image dimensions
$width = $image->getImageWidth();
$height = $image->getImageHeight();

// Create a new Imagick object with a white background of the same size as the image
$background = new \Imagick();
$background->newImage($width, $height, 'white', 'png');

// Add the image to the background
$background->compositeImage($image, \Imagick::COMPOSITE_OVER, 0, 0);

// Convert the image to grayscale
$background->modulateImage(100, 0, 100);

// Get the histogram of the image
$histogram = $background->getImageHistogram();

// Count the number of pixels at each intensity level
$count = array_fill(0, 256, 0);
foreach ($histogram as $pixel) {
    $color = $pixel->getColor();
    $intensity = round(($color['r'] + $color['g'] + $color['b']) / 3);
    $count[$intensity] += $pixel->getColorCount();
}

// Calculate the total number of pixels
$totalPixels = $width * $height;

// Calculate the total number of dark pixels (intensity < 128)
$darkPixels = array_sum(array_slice($count, 0, 128));

// Calculate the total number of light pixels (intensity >= 128)
$lightPixels = array_sum(array_slice($count, 128));

// Determine if the image is light or dark
$isLight = ($lightPixels / $totalPixels) > 0.5;

// Output the result
if ($isLight) {
    echo 'The image is light';
} else {
    echo 'The image is dark';
}

请注意,这种方法可能不适用于具有大量透明区域的图像,因为这些区域可能会使直方图偏向一端或另一端。在这些情况下,您可能需要想出一个更复杂的算法来考虑每个像素的透明度。

© www.soinside.com 2019 - 2024. All rights reserved.