I’ve consulted the PHP manual to try and invert the colors of an image, but I can’t get the image to display the way I need it to.
Essentially, within a WordPress loop, I need to take an image, invert it, and then set the background image of a div to that inverted image. Here’s my code so far:
<?
if (have_rows("slideshow")):
while (have_rows("slideshow")):
the_row();
$icon = get_sub_field("icon");
$image = get_sub_field("image");
?>
<button data-slide="<? echo $image["url"] ?>">
<div class="icon" style="background-image:url('<? echo $icon["url"] ?>');">
<?
function negate($im) {
if (function_exists("imagefilter")) {
return imagefilter($im, IMG_FILTER_NEGATE);
}
for ($x = 0; $x < imagesx($im); ++$x) {
for ($y = 0; $y < imagesy($im); ++$y) {
$index = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($index);
$color = imagecolorallocate($im, 255 - $rgb["red"], 255 - $rgb["green"], 255 - $rgb["blue"]);
imagesetpixel($im, $x, $y, $color);
}
}
return(true);
}
$im = imagecreatefrompng($icon["url"]);
if ($im && negate($im)) {
echo "Image successfully converted to negative colors.";
imagepng($im);
imagedestroy($im);
}
?>
<!--<span style="background-image:url('img/icon-circle-white.png');"></span>-->
</div><!--/.icon-->
<div class="caption">
<h2><? the_sub_field("title"); ?></h2>
<? the_sub_field("caption"); ?>
</div><!--/.caption-->
</button>
<?
endwhile;
endif;
?>
This works, but it spits out a bunch of weird characters instead of the image. It seems to me that the problem is imagepng()
requires header("Content-type: image/png");
, but I can’t do that because this is within a WordPress loop, not a separate file.
My idea is to externalize the image inversion stuff, and run that separate PHP against every image that I specify in the loop (ex: <img src="/invert.php?url=<? $icon['url'] ?>" />
. Unfortunately I don’t know how to do that.
Is this possible?
One solution is to deploy the image-data inline like so:
This does have some downsides:
Hope this helps.