PHP GD: Multiply image colors with tint color

ε祈祈猫儿з 提交于 2019-12-12 04:46:13

问题


can I use GD to multiply given color (RGB) with every pixel of an image resource (RGBA)? For example, if the given tint color is red (255, 0, 0), a black pixel on the image resource should stay black (since 255 * 0 = 0) and brighter pixels should be affected more by that red tint factor.

I tried

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

but that only changes black pixels. NEGATE, IMG_FILTER_COLORIZE, NEGATE also won't work.


回答1:


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.';
}

?>


来源:https://stackoverflow.com/questions/26005991/php-gd-multiply-image-colors-with-tint-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!