PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 19, 2022

[FIXED] How to mask an image with a composite but only where the color is black

 September 19, 2022     imagick, php     No comments   

Issue

I have a mask.png:

mask

And some other png image with the same dimensions:

image

Now I would like to mask the image with mask.png but only where the color is black on the mask image.

Desired result:

desired result

Is something like this possible with imagick if yes how?


Solution

This is a really tricky question. Usually to isolate black colors, you would simply apply a SCREEN composite.

$image->compositeImage($mask, Imagick::COMPOSITE_SCREEN, 0, 0);

But the mask in question already has an active alpha channel, so it may be possible that transparent black values exists, and cause undesired effects.

I would suggest rebuilding the mask as a new alpha color channel. That is to say, a black-n-white image where black represents a fully opaque pixel, and white is a fully transparent pixel. Then copy the rebuilt mask as the new alpha channel.

// Load resources.
$image = new Imagick('input.png');
$mask = new Imagick('mask.png');
// Create a white canvas.
$tempMask = new Imagick();
$tempMask->newPseudoImage($mask->width, $mask->height, 'XC:WHITE');
// Copy mask over canvas to replace transparent values.
$tempMask->compositeImage($mask, Imagick::COMPOSITE_ATOP, 0, 0);
// Invert colors.
$tempMask->negateImage(true);
// Copy temporary mask as the new alpha channel.
$image->compositeImage($tempMask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);
// Save results.
$image->writeImage('output.png');

output.png



Answered By - emcconville
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing