Search code examples
phpimageimage-processinggd

PHP : Convert dynamic uploaded image to specific color(dynamic color)


I have a simple HTML form where the user can upload their image and I need to convert this uploaded image into a specific color with the help of PHP

For example, user upload some image I need to convert the entire image into a specific color (this color is dynamic)

Is there any PHPGD library that can help me to achieve this?

EDIT

For example, user is uploading this kind of Image,

enter image description here

then I need to convert into below type of Image,

enter image description here


Solution

  • I'm still unsure exactly what you are trying to do, but think one of the following may be close. Maybe you can try them in the Terminal until we can finally work out the correct operations then we can hopefully translate them into PHP. This is ImageMagick v7 syntax:

    magick image.png -channel RGB -colorspace gray +level-colors red,  result.png
    

    enter image description here

    Or this:

    magick image.png -fill red +opaque white result2.png
    

    enter image description here

    You can specify the colour in hex like this for magenta:

    magick image.png -channel RGB -colorspace gray -auto-level +level-colors '#ff00ff',  result.png
    

    If using v6 ImageMagick, replace magick with convert.


    My PHP is pretty rusty, but something like this:

    #!/usr/local/bin/php -f
    <?php
    
    // Emulating something akin to this ImageMagick command:
    // magick image.png -fill red +opaque white result.png
    // Open input image and get dimensions
    $im = new \Imagick('image.png');
    
    // Temporarily deactivate alpha channel
    $im->setImageAlphaChannel(Imagick::ALPHACHANNEL_DEACTIVATE);
    
    // Apply colour to non-white areas
    $im->opaquePaintImage('white','red', 0, true);
    
    // Reactivate alpha channel
    $im->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);
    
    // Save
    $im->writeImage('result.png');
    ?>