php - 如何使用php更改png图像像素值
问题描述
我正在尝试将图像中的白色像素更改为黑色,但我在设置颜色格式时遇到了困难imagesetpixel
在做什么
// get image data
$image_data = imagecreatefrompng($image);
// Turn off alpha blending
imagealphablending($image_data, false);
$width = imagesx($image_data);
$height = imagesy($image_data);
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
// pixel color at (x, y)
$color = imagecolorsforindex($image_data, imagecolorat($image_data, $x, $y)); // human readable
// check if we have white
if(
$color['red'] == 255 &&
$color['green'] == 255 &&
$color['blue'] == 255 &&
$color['alpha'] == 127
){
// make it black
$color['red'] == 0
$color['green'] == 0
$color['blue'] == 0
imagesetpixel($image_data, $x, $y, $color ); // $color format not OK.
}
}
}
// Set alpha flag
imagesavealpha($image_data, true);
// https://www.php.net/manual/en/function.imagepng.php
imagepng($image_data , "path to save png");
imagedestroy($image_data);
所以知道我们如何将imagecolorsforindex
返回格式转换为与imagesetpixel
.
解决方案
// make it black
$color['red'] == 0
$color['green'] == 0
$color['blue'] == 0
imagesetpixel($image_data, $x, $y, $color ); // $color format not OK.
不遵循imagesetpixel
错误指示的样式:
未捕获的 TypeError: imagesetpixel(): 参数 #4 ($color) 必须是 int 类型,给定数组
让我们解决这个问题,考虑以下示例:
// Create black color (rgb)
$black = imagecolorallocate($image_data, 0, 0, 0);
// Make it black
imagesetpixel($image_data, $x, $y, $black);
在这里,我们imagecolorallocate
用来创建imagesetpixel
接受颜色的“黑色”。
和很好$image_data
,我们将x
保持y
原样。
另外,我创建了一个简单的测试图像来检查它是否正常工作,但是,您的检查没有触发由 MacOs 预览创建的简单白色像素,alpha
设置为0
,因此对于我的测试,我将进行以下更改:
if(
$color['red'] == 255 &&
$color['green'] == 255 &&
$color['blue'] == 255 // &&
// $color['alpha'] == 127
)
推荐阅读
- javascript - 这段代码“var FileStore = require('session-file-store')(session);”是什么意思?
- apache-kafka - 在 Kafka Connect 日志中屏蔽?
- html - CSS:如何根据 class/id 自定义滚动条填充和边距
- java - 铸造泛型
- php - 本地主机的 Htaccess 重写规则
- angular - cordova InAppPurchase 插件给出错误“错误类型错误:无法读取未定义的属性'getProducts'”
- amazon-web-services - 基于多个文件触发 Lambda
- python - zsh:找不到命令:烧瓶
- authentication - apiplatform-react admin:localstorage中的token在重定向时为null,必须刷新页面
- django - Django 错误:save() 得到了一个意外的关键字参数“toppings”