Created
July 13, 2012 20:40
-
-
Save bobmagicii/3107329 to your computer and use it in GitHub Desktop.
Setting image opacity in Imagick (good result)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function bob_opacity($img,$alpha) { | |
if(!is_object($img)) return false; | |
if($alpha > 1 || $alpha < 0) return false; | |
$rows = $img->getPixelIterator(); | |
foreach($rows as $cols) { | |
foreach($cols as $pixel) { | |
// we now have an object pointing at a single pixel of the image | |
// which we can then manipulate. the $pixel. | |
// so find out the pixels current transparency level. | |
$current = $pixel->getColorValue(Imagick::COLOR_ALPHA); | |
// only make the pixel more transparent than it may already be | |
// if the resulting value is greater than fully transparent. | |
$pixel->setColorValue( | |
Imagick::COLOR_ALPHA, | |
(($current - $alpha > 0)?($current - $alpha):(0)) | |
); | |
// tell imagick to sync the change made to the pixel object to | |
// the actual image, via the iterator that created the pixel | |
// object. | |
$rows->syncIterator(); | |
} | |
} | |
return true; | |
} | |
$img = new Imagick('input.png'); | |
bob_opacity($img,0.75); // make it 75% more transparent. | |
$img->writeImage('output-good.png'); | |
$img->destroy(); | |
?> |
11 years later and you've saved my day. Thanks!
roflmao im sorry you couldn't have witnessed one written slightly nicer format that 2023 me would write. but the logic is still valid.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
11 years later and you've saved my day. Thanks!