PHP GD: Multiplying the Colors of an Image with a Tint of Color

Can I use GD to multiply a given color (RGB) by each pixel of an image resource (RGBA)? For example, if the specified shade of red (255, 0, 0), the black pixel on the image resource should remain black (with 255 * 0 = 0), and brighter pixels should be more prone to this red color coefficient.

I tried

imagefilter($sprite, IMG_FILTER_COLORIZE, 255, 0, 0);

but it only changes the black pixels. NEGATE, IMG_FILTER_COLORIZE, NEGATE will not work either.

0
source share
1 answer

This seems to work for me:

<?php
// function for creating images from any uploaded

function imageCreateFromAny($filepath) { 

    $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize() 
    $allowedTypes = array( 
        1,  // [] gif 
        2,  // [] jpg 
        3,  // [] png 
        6   // [] bmp 
    ); 
    if (!in_array($type, $allowedTypes)) { 
    return false; 
    } 
    switch ($type) { 
        case 1 : 
            $im = imageCreateFromGif($filepath); 
        break; 
        case 2 : 
            $im = imageCreateFromJpeg($filepath); 
        break; 
        case 3 : 
            $im = imageCreateFromPng($filepath); 
        break; 
        case 6 : 
            $im = imageCreateFromBmp($filepath); 
        break; 
    }    
    return $im;  
}

// set up variables
$filter_r=255;
$filter_g=0;
$filter_b=0;
$suffixe="-red";
$path="original-source/image.jpg";

if(is_file($path)){
    $image=imageCreateFromAny($path);

    // invert inteded color "red"
    $filter_r_opp = 255 - $filter_r; // = 0
    $filter_g_opp = 255 - $filter_g; // = 255
    $filter_b_opp = 255 - $filter_b; // = 255
    // color is now "aqua"

    /* FAST METHOD */
    imagefilter($image, IMG_FILTER_NEGATE);
    imagefilter($image, IMG_FILTER_COLORIZE, $filter_r_opp, $filter_g_opp, $filter_b_opp);
    imagefilter($image, IMG_FILTER_NEGATE);

    $new_path=substr($path,0,strlen($path)-4).$suffixe.".jpg";
    imagejpeg($image,$new_path);

    imagedestroy($image);

    echo 'Red shading success.';
}
else {
    echo 'Red shading failed.';
}

?>
0
source

All Articles