Jac*_*Dev 1 php wordpress image
我已经查阅了 PHP 手册来尝试反转图像的颜色,但我无法让图像以我需要的方式显示。
本质上,在 WordPress 循环中,我需要拍摄一个图像,将其反转,然后将 div 的背景图像设置为该反转图像。到目前为止,这是我的代码:
<?
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;
?>
Run Code Online (Sandbox Code Playgroud)
这有效,但它吐出一堆奇怪的字符而不是图像。在我看来,问题是imagepng()requires header("Content-type: image/png");,但我不能这样做,因为这是在 WordPress 循环中,而不是单独的文件。
我的想法是外部化图像反转的东西,并针对我在循环中指定的每个图像运行单独的 PHP(例如:<img src="/invert.php?url=<? $icon['url'] ?>" />。不幸的是我不知道如何做到这一点。
这可能吗?
一种解决方案是像这样内联部署图像数据:
<?php
//...
$im = imagecreatefrompng($icon["url"]);
if ($im && negate($im)) {
echo "Image successfully converted to negative colors.";
//read the imagedata into a variable
ob_start();
imagepng($im);
$imgData=ob_get_clean();
imagedestroy($im);
//Echo the data inline in an img tag with the common src-attribute
echo '<img src="data:image/png;base64,'.base64_encode($imgData).'" />';
}
//...
?>
Run Code Online (Sandbox Code Playgroud)
这确实有一些缺点:
希望这可以帮助。