首页 > 解决方案 > 如何使用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.

标签: php

解决方案


//  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
)

推荐阅读