Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a little upgrade to this script - I found that if the source image has transparency itself, the mask (using the script above) plots a back pixel instead of the source image's transparent pixel. The below extended script takes source image transparency into consideration, and preserves it.</p> <pre><code>// Load source and mask $source = imagecreatefrompng( '1.png' ); $mask = imagecreatefrompng( '2.png' ); // Apply mask to source imagealphamask( $source, $mask ); // Output header( "Content-type: image/png"); imagepng( $source ); function imagealphamask( &amp;$picture, $mask ) { // Get sizes and set up new picture $xSize = imagesx( $picture ); $ySize = imagesy( $picture ); $newPicture = imagecreatetruecolor( $xSize, $ySize ); imagesavealpha( $newPicture, true ); imagefill( $newPicture, 0, 0, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) ); // Resize mask if necessary if( $xSize != imagesx( $mask ) || $ySize != imagesy( $mask ) ) { $tempPic = imagecreatetruecolor( $xSize, $ySize ); imagecopyresampled( $tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx( $mask ), imagesy( $mask ) ); imagedestroy( $mask ); $mask = $tempPic; } // Perform pixel-based alpha map application for( $x = 0; $x &lt; $xSize; $x++ ) { for( $y = 0; $y &lt; $ySize; $y++ ) { $alpha = imagecolorsforindex( $mask, imagecolorat( $mask, $x, $y ) ); if(($alpha['red'] == 0) &amp;&amp; ($alpha['green'] == 0) &amp;&amp; ($alpha['blue'] == 0) &amp;&amp; ($alpha['alpha'] == 0)) { // It's a black part of the mask imagesetpixel( $newPicture, $x, $y, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) ); // Stick a black, but totally transparent, pixel in. } else { // Check the alpha state of the corresponding pixel of the image we're dealing with. $alphaSource = imagecolorsforindex( $source, imagecolorat( $source, $x, $y ) ); if(($alphaSource['alpha'] == 127)) { imagesetpixel( $newPicture, $x, $y, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) ); // Stick a black, but totally transparent, pixel in. } else { $color = imagecolorsforindex( $source, imagecolorat( $source, $x, $y ) ); imagesetpixel( $newPicture, $x, $y, imagecolorallocatealpha( $newPicture, $color[ 'red' ], $color[ 'green' ], $color[ 'blue' ], $color['alpha'] ) ); // Stick the pixel from the source image in } } } } // Copy back to original picture imagedestroy( $picture ); $picture = $newPicture; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload