Mask over image

204 views Asked by At

I want to replace the transparent pixels of a image with a mask, I'm using this function but I keep getting errors.

When I try:

<?php

function image_mask($src, $mask)
{


imagesavealpha($src, true);
imagealphablending($src, false);
// scan image pixels
// imagesx = get image width
for ($x = 0; $x < imagesx($src); $x++) {
    // imagesy = get image height
    for ($y = 0; $y < imagesy($src); $y++) {
        $mask_pix = imagecolorat($mask,$x,$y);
        //return r,g,b,alpha
        $mask_pix_color = imagecolorsforindex($mask, $mask_pix);
        if ($mask_pix_color['alpha'] < 127) {
            $src_pix = imagecolorat($src,$x,$y);
            $src_pix_array = imagecolorsforindex($src, $src_pix);
            imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
        }
    }
}

}
image_mask('source.png', 'mask.png');

?>

I get the following errors:

Warning: imagesavealpha() expects parameter 1 to be resource, string given in ... on line 7

Warning: imagealphablending() expects parameter 1 to be resource, string given in ... on line 8

Warning: imagesx() expects parameter 1 to be resource, string given in ... on line 11

I tried adding imageCreateFromPng and header('Content-Type: image/png'); to the images but then I just get a empty page.

2

There are 2 answers

1
phplx On

“imagesavealpha() expects parameter 1 to be resource, string given” the gaved param 1 of imagesavealpha is wrong, it need resource,the resource may imagecreatetruecolor/imagecreatefrompng create

0
phplx On

i don`t know what result were you want get , and i feel the page show is wrong . you can try run the program

<?php

header('Content-Type: image/png');

function image_mask(&$src, &$mask)
{

    imagesavealpha($src, true);
    imagealphablending($src, false);
    // scan image pixels
    // imagesx = get image width
    for ($x = 0; $x < imagesx($src); $x++) {
        // imagesy = get image height
        for ($y = 0; $y < imagesy($src); $y++) {
            $mask_pix = imagecolorat($mask,$x,$y);
            //return r,g,b,alpha
            $mask_pix_color = imagecolorsforindex($mask, $mask_pix);
            if ($mask_pix_color['alpha'] < 127) {
                $src_pix = imagecolorat($src,$x,$y);
                $src_pix_array = imagecolorsforindex($src, $src_pix);
                imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
            }
        }
    }

}

$src = imagecreatefrompng('source.png');
$mask = imagecreatefrompng('mask.png');

image_mask($src, $mask);

imagepng($src);

imagedestroy($src);
imagedestroy($mask);

  ?>