转换为灰度php后将新图像数据写入文件
Im使用以下代码拍摄图像,将其转换为灰度,然后保存灰度图像:转换为灰度php后将新图像数据写入文件,php,Php,Im使用以下代码拍摄图像,将其转换为灰度,然后保存灰度图像: $imagename = "$imagename"; // path to previously uploaded color jpeg $im = ImageCreateFromJpeg($imagename); $imgw = imagesx($im); $imgh = imagesy($im); for ($i=0; $i<$imgw; $i++) {
$imagename = "$imagename"; // path to previously uploaded color jpeg
$im = ImageCreateFromJpeg($imagename);
$imgw = imagesx($im);
$imgh = imagesy($im);
for ($i=0; $i<$imgw; $i++)
{
for ($j=0; $j<$imgh; $j++)
{
$rgb = ImageColorAt($im, $i, $j);
$rr = ($rgb >> 16) & 0xFF;
$gg = ($rgb >> 8) & 0xFF;
$bb = $rgb & 0xFF;
$g = round(($rr + $gg + $bb) / 3);
$val = imagecolorallocate($im, $g, $g, $g);
imagesetpixel ($im, $i, $j, $val);
}
}
$grayimgpath = "step2cache/".$saltname."_gray.jpg"; //$saltname is a randomly generated image name
$fh = fopen($grayimgpath, 'w') or die("can't open file");
fwrite($fh, $im);
fclose($fh);
$imagename=“$imagename”;//以前上载的彩色jpeg的路径
$im=ImageCreateFromJpeg($imagename);
$imgw=imagesx($im);
$imgh=imagesy($im);
对于($i=0;$i 16)&0xFF;
$gg=($rgb>>8)和0xFF;
$bb=$rgb&0xFF;
$g=圆形($rr+$gg+$bb)/3);
$val=imagecolorallocate($im,$g,$g,$g);
imagesetpixel($im,$i,$j,$val);
}
}
$grayimgpath=“step2cache/”$saltname.\u gray.jpg”//$saltname是随机生成的图像名称
$fh=fopen($grayimgpath,'w')或die(“无法打开文件”);
fwrite($fh,$im);
fclose($fh);
问题是,当我访问这个文件时,它是空白的,15个字节
我在这里遗漏了什么?您不能只将图像对象写入文件。GD库中有相应的函数。因此,您应该在第二个参数中使用with filename,而不是
fopen
和fwrite
:
imagejpeg($im, $grayimgpath);
不能只将图像对象写入文件。GD库中有相应的函数。因此,您应该在第二个参数中使用with filename,而不是
fopen
和fwrite
:
imagejpeg($im, $grayimgpath);
您正在尝试向文件写入图像句柄,而不是实际的图像数据。试试这个:
imagejpeg($im, $grayimgpath);
您正在尝试向文件写入图像句柄,而不是实际的图像数据。试试这个:
imagejpeg($im, $grayimgpath);
$im
不是文件的二进制内容,而是包含GD定义的某些内部结构的PHP对象。当您将其写入文件时,您将写入其文本表示形式,可能与(string)$im
$im
相同。它不是文件的二进制内容,而是包含GD定义的某些内部结构的PHP对象。当您将其写入文件时,您将写入其文本表示形式,可能与(string)$im
相同。