【问题标题】:PHP remove a section of image leaving a transparent spacePHP删除一部分图像留下透明空间
【发布时间】:2016-06-04 08:30:28
【问题描述】:

我有一个透明的图像,中间有一个条... http://i66.tinypic.com/2zyeg4h.png

使用php我想去掉bar中间的部分,在bar中间留下一个透明的空间。我试试这段代码...

$im = imagecreatefrompng('****root****/image.png');
//make a yellow box
$transparent = imagecolorallocate($im, 255, 255, 0);
//make the yellow box transparent
imagecolortransparent($im, $transparent);
imagefilledrectangle($im, 200, 115, 300, 137, $transparent);

imagealphablending($im, false);
imagesavealpha($im, true);

header ('Content-Type: image/png');

imagepng($im);

$save = "****root****/test.png";
imagepng($im, $save);
imagedestroy($im);
?>

但输出图像的矩形保留黄色,而不是使其透明。

http://i67.tinypic.com/1ny6j4.png

我哪里错了?如果我删除...

 imagealphablending($im, false);
 imagesavealpha($im, true);

我得到了中心的透明框(在浏览器中),但是图像的其余部分失去了透明度,而是变成了白色背景,当我下载该图像并在照片编辑器中打开时,透明度框在中心不见了。我在我的服务器上设置了 GD 库。

【问题讨论】:

标签: php


【解决方案1】:

你需要使用gd函数imagecolorallocatealpha来创建透明色。

您可以使用 PHP 生成整个图像。

例如

<?php
// generate empty image
$image = imagecreate(500, 262);

// define black
$black = imagecolorallocate($image, 0, 0, 0);

// create left part of the bar
imagefilledrectangle($image, 0, 110, 200, 162, $black);

// create right part of the bar
imagefilledrectangle($image, 300, 110, 500, 162, $black);

// save image
imagepng($image, 'outimage.png');

如果您想坚持使用现有图像

<?php
// generate empty image
$image = imagecreatefrompng('input.png');

// define transparent
$transparent = imagecolorallocatealpha($image, 255, 255, 255, 127);

// create the transparent area
imagefilledrectangle($image, 200, 110, 300, 162, $transparent);

// save image
imagepng($image, 'output.png');

输入.png

输出.png

如果您没有将图像作为结果提交给浏览器,则无需发送标头。

例如

header('Content-Type: image/png');
imagepng($image);

将在请求浏览器中显示图像,而不是将其保存到文件中。

【讨论】:

  • 嗨,米歇尔,非常感谢您的帮助!我使用现有图像尝试了您的代码,尽管输出文件似乎没有透明矩形切出条形图,图像看起来相同...i66.tinypic.com/2zyeg4h.png。我也尝试了一个纯黑色图像作为输入,但它只输出相同的纯黑色图像,没有透明的矩形被剪掉。为什么代码对我不起作用?
  • 第一个与你的完全一样粘贴的脚本会输出一个 500x 262 像素的纯黑色图像,对我来说没有透明度。
  • 如果执行这里的示例,是否得到示例图像? php.net/manual/en/function.imagecolorallocatealpha.php
  • 您使用的是哪个 PHP/GD 版本和哪个操作系统?
  • 来自 gd_info() ... array(12) { ["GD 版本"]=> string(26) "bundled (2.1.0 compatible)" ["FreeType Support"]=> bool (true) ["FreeType Linkage"]=> string(13) "with freetype" ["T1Lib Support"]=> bool(false) ["GIF Read Support"]=> bool(true) ["GIF Create Support" ]=> bool(true) ["JPEG 支持"]=> bool(true) ["PNG 支持"]=> bool(true) ["WBMP 支持"]=> bool(true) ["XPM 支持"]= > bool(true) ["XBM Support"]=> bool(true) ["JIS-mapped Japanese Font Support"]=> bool(false) } 当前 PHP 版本:5.4.452.0 Linux CENTOS 6.8
猜你喜欢
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
相关资源
最近更新 更多