Skip to content

Instantly share code, notes, and snippets.

@Waicung
Created January 17, 2018 04:02
Show Gist options
  • Save Waicung/89fa75233ac217f58c08c0484fc1fd6e to your computer and use it in GitHub Desktop.
Save Waicung/89fa75233ac217f58c08c0484fc1fd6e to your computer and use it in GitHub Desktop.
<?php
/**
* the image object
* e.g. imagecreatefrompng('path/to/image.png')
* @param $im
* sample position of an image
* @param $x
* @param $y
*
* @return float
*/
function getgray($im, $x, $y) {
//获取($x, $y)处的rgb值
$rgb = imagecolorat($im, $x, $y);
//计算灰度
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8 ) & 0xFF;
$blue = $rgb & 0xFF;
$gray = round(.299*$red + .587*$green + .114*$blue);
return $gray;
}
/**
* the image object
* e.g. imagecreatefrompng('path/to/image.png')
* @param $im
* sampling starting/ending point
* @param $x
* @param $y
* dimension of the sampling area
* @param $width
* @param $height
* whether the starting/ending point
* @param bool $end
*
* @return float|int
*/
function getAvgGray($im, $x, $y, $width, $height, $end=false) {
$avggray = $gray = 0;
if ($end) {
//当传入的($x, $y)坐标为结束位置时 则结束位置为($x,$y)
$x_width = $x;
$y_height = $y;
//开始位置 (结束位置 - 水印宽高)
$x = $x - $width; $y = $y - $height;
} else {
$x_width = $x+$width;
$y_height = $y+$height;
}
$index=0;
for ($i = $x; $i <= $x_width; $i++) {
for ($j = $y; $j <= $y_height; $j++) {
$gray += getgray($im, $i, $j);
print('index:'.$index.' x:'.$i.'; y:'.$j.' '.$gray.'<br>');
$index +=1;
}
}
var_dump(($width+1)*($height+1));
$avggray = round($gray/(($width+1)*($height+1)));
return $avggray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment