如何检查图像是单色还是空白?
How to check if and image is mono color or empty?
我需要阻止用户上传空白的个人资料图片。对于空白图像,我指的是全白或任何其他全彩色图像。
我认为最好的方法是检查图像是否只包含一种颜色,但我不知道该怎么做。
我正在尝试在图片上传后进行检查,只是为了简化操作。
谁能帮我解决这个问题?
检查整个图像
1) 将您的图像调整为更小的尺寸(例如将其调整为 originalSize/10 或类似这样...)
2) 使用 this function 获取图像大小
3)遍历像素,保存第一个像素的颜色并继续直到位置 x,y 上的像素颜色不同或直到没有更多像素未选中。
<?php
function isColorSame($imgname){
$img = imagecreatefrompng($imgname);
list($width, $height, $type, $attr) = getimagesize($imgname);
$x = 0;
$y = 0;
$starterColor = imagecolorat(0, 0, $img);
while($x < $width){
while($y < $height) {
if (imagecolorat($x, $y, $img) !== $starterColor){
return false;
}
$y++;
}
$x++;
}
return true;
}
猜猜
通过生成随机 x,y 并检查此位置的颜色,仅检查几个像素(例如 100 个像素)。这不是 100% 确定,但在此之后,您可以将图像传递给函数,该函数会检查所有像素。
我需要阻止用户上传空白的个人资料图片。对于空白图像,我指的是全白或任何其他全彩色图像。 我认为最好的方法是检查图像是否只包含一种颜色,但我不知道该怎么做。
我正在尝试在图片上传后进行检查,只是为了简化操作。
谁能帮我解决这个问题?
检查整个图像
1) 将您的图像调整为更小的尺寸(例如将其调整为 originalSize/10 或类似这样...) 2) 使用 this function 获取图像大小 3)遍历像素,保存第一个像素的颜色并继续直到位置 x,y 上的像素颜色不同或直到没有更多像素未选中。
<?php
function isColorSame($imgname){
$img = imagecreatefrompng($imgname);
list($width, $height, $type, $attr) = getimagesize($imgname);
$x = 0;
$y = 0;
$starterColor = imagecolorat(0, 0, $img);
while($x < $width){
while($y < $height) {
if (imagecolorat($x, $y, $img) !== $starterColor){
return false;
}
$y++;
}
$x++;
}
return true;
}
猜猜
通过生成随机 x,y 并检查此位置的颜色,仅检查几个像素(例如 100 个像素)。这不是 100% 确定,但在此之后,您可以将图像传递给函数,该函数会检查所有像素。