I have searched a lot and I found only few solutions (on google and stackoverflow so please don\'t mark this one as a duplicate unless there\'s really duplicate question), b
This code doesn't exemplify the problem, but transforms colors like this:
Uses the ALPHA channel of an image to determines coloring. For other results, just play around with imagecolorallocatealpha()
:
function colorizeBasedOnAplhaChannnel( $file, $targetR, $targetG, $targetB, $targetName ) {
$im_src = imagecreatefrompng( $file );
$width = imagesx($im_src);
$height = imagesy($im_src);
$im_dst = imagecreatefrompng( $file );
// Note this:
// Let's reduce the number of colors in the image to ONE
imagefilledrectangle( $im_dst, 0, 0, $width, $height, 0xFFFFFF );
for( $x=0; $x<$width; $x++ ) {
for( $y=0; $y<$height; $y++ ) {
$alpha = ( imagecolorat( $im_src, $x, $y ) >> 24 & 0xFF );
$col = imagecolorallocatealpha( $im_dst,
$targetR - (int) ( 1.0 / 255.0 * $alpha * (double) $targetR ),
$targetG - (int) ( 1.0 / 255.0 * $alpha * (double) $targetG ),
$targetB - (int) ( 1.0 / 255.0 * $alpha * (double) $targetB ),
$alpha
);
if ( false === $col ) {
die( 'sorry, out of colors...' );
}
imagesetpixel( $im_dst, $x, $y, $col );
}
}
imagepng( $im_dst, $targetName);
imagedestroy($im_dst);
}
unlink( dirname ( __FILE__ ) . '/newleaf.png' );
unlink( dirname ( __FILE__ ) . '/newleaf1.png' );
unlink( dirname ( __FILE__ ) . '/newleaf2.png' );
$img = dirname ( __FILE__ ) . '/leaf.png';
colorizeBasedOnAplhaChannnel( $img, 0, 0, 0xFF, 'newleaf1.png' );
colorizeBasedOnAplhaChannnel( $img, 0xFF, 0, 0xFF, 'newleaf2.png' );
?>
Original