我正在寻找一个在PHP中提取图像直方图并将其转换为PNG文件的函数。这个PNG文件需要位于与实际图像不同的文件夹中,而且该函数必须处理大型图像(超过3 MB)。我发现了一个几乎符合我的要求的函数,但是该函数无法处理大型图像,并且它没有像网站上展示的那样展示出直方图或者图像(它只显示了一个带边框的空白窗口)。
我希望你们能帮助我解决这个问题。
谢谢。
我希望你们能帮助我解决这个问题。
谢谢。
这是一个编写简单直方图的脚本,就像Photoshop一样(只是类似,因为我怀疑它使用了sigmoid函数或类似的方法来缩放两个轴)。
我编写了一个scale()
函数,您可以使用最后一个bool参数制作线性直方图,或者使用平方根比例来提高低值。
<?php
//Just in case GD needs more memory
ini_set('memory_limit', '64M');
$filename='image1.png';
//Attempt to open
[$width, $height, $type]=getimagesize($filename);
if($type==IMAGETYPE_PNG){
$img=imagecreatefrompng($filename);
}
//Histogram initialization
$hist = array(
'red'=>array_fill(0,256,0),
'green'=>array_fill(0,256,0),
'blue'=>array_fill(0,256,0)
);
//Counting colors
for($x=0;$x<$width;++$x){
for($y=0;$y<$height;++$y){
$bytes=imagecolorat($img,$x,$y);
$colors=imagecolorsforindex($img,$bytes);
++$hist['red'][$colors['red']];
++$hist['green'][$colors['green']];
++$hist['blue'][$colors['blue']];
}
}
//Drawing histogram as a 256x128px image
$width=256;
$height=128;
$newimg=imagecreatetruecolor($width,$height);
//Max frequency for normalization
$maxr=max($hist['red']);
$maxg=max($hist['green']);
$maxb=max($hist['blue']);
$max=max($maxr,$maxg,$maxb);
function scale($value,$max,$height,$scale=FALSE){
$result=$value/$max; //normalization: value between 0 and 1
$result=$scale?$result**0.5:$result; //sqrt scale
$result=$height-round($result*$height); //scaling to image height
return $result;
}
$top=220; //255 seems too bright to me
for($x=0;$x<$width;++$x){
for($y=0;$y<$height;++$y){
$r=($y>scale($hist['red'][$x],$maxr,$height,TRUE))?$top:0;
$g=($y>scale($hist['green'][$x],$maxg,$height,TRUE))?$top:0;
$b=($y>scale($hist['blue'][$x],$maxb,$height,TRUE))?$top:0;
$colors=imagecolorallocate($newimg,$r,$g,$b);
imagesetpixel($newimg,$x,$y,$colors);
}
}
//Saving the histogram as you need
imagepng($newimg,'.subfolder/histogram.png');
//Use the next lines, and remove the previous one, to show the histogram image instead
//header('Content-Type: image/png');
//imagepng($newimg);
exit();
?>
getimagesize()
或imagecreatefrompng()
是否失败。我用一张2MB(5800 x 5800)的PNG图像进行了测试。基本上,“imagecreatefrompng()”方法消耗了大量内存。
因此,在调用之前,我将内存增加到512M,并将执行时间设置为5分钟。
ini_set('memory_limit', '512M');
set_time_limit(5*60);
在图像创建完成后,恢复内存限制
$im = ImageCreateFromPng($source_file);
ini_restore('memory_limit');
参考资料:http://www.php.net/manual/zh/function.imagecreatefrompng.php#73546