2009-06-26 112 views
3

第一个问题,请温柔;-)如何挑选颜色使图像变得透明?

我写的图像类,使简单的事情(矩形,文字)更容易一点,基本上是一堆包装方法对PHP的图像功能。
我现在要做的就是让用户定义一个选区,并让下列图像操作只影响选定的区域。我想我会通过将图像复制到imgTwo并从中删除所选区域来完成此操作,像往常一样对原始图像执行以下图像操作,然后当调用$ img-> deselect()时,将imgTwo复制回原始,并销毁该副本。

  • 这是最好的方法吗?显然这将是棘手的一个选定的区域内定义取消选定的区域,但我现在可以忍受:)

然后,我从擦除副本中选择的方式是绘制一个矩形透明颜色,这是工作 - 但我不知道如何选择该颜色,同时确保它不会发生在图像的其余部分。这个应用程序中的输入图像是真彩色PNG,所以没有带颜色索引的调色板(我认为?)。

  • 要收集每个像素的颜色,然后找到没有出现在$ existing_colours数组中的颜色,必须有更好的方法..对吗?

回答

3

PNG透明度对GIF透明度的工作方式不同 - 您不需要将特定颜色定义为透明。 只需使用imagecolorallocatealpha(),并确保你已经设置imagealphablending()false

// "0, 0, 0" can be anything; 127 = completely transparent 
$c = imagecolorallocatealpha($img, 0, 0, 0, 127); 

// Set this to be false to overwrite the rectangle instead of drawing on top of it 
imagealphablending($img, false); 

imagefilledrectangle($img, $x, $y, $width - 1, $height - 1, $c); 
+0

干杯,似乎工作,但我不得不添加imagecolortransparent($ img,$ c);这听起来正确吗? – MSpreij 2009-06-27 23:46:20

0

的代码最终看上去像这样:

# -- select($x, $y, $x2, $y2) 
function select($x, $y, $x2, $y2) { 
    if (! $this->selected) { // first selection. create new image resource, copy current image to it, set transparent color 
    $this->copy = new MyImage($this->x, $this->y); // tmp image resource 
    imagecopymerge($this->copy->img, $this->img, 0, 0, 0, 0, $this->x, $this->y, 100); // copy the original to it 
    $this->copy->trans = imagecolorallocatealpha($this->copy->img, 0, 0, 0, 127); // yep, it's see-through black 
    imagealphablending($this->copy->img, false);         // (with alphablending on, drawing transparent areas won't really do much..) 
    imagecolortransparent($this->copy->img, $this->copy->trans);     // somehow this doesn't seem to affect actual black areas that were already in the image (phew!) 
    $this->selected = true; 
    } 
    $this->copy->rect($x, $y, $x2, $y2, $this->copy->trans, 1); // Finally erase the defined area from the copy 
} 

# -- deselect() 
function deselect() { 
    if (! $this->selected) return false; 
    if (func_num_args() == 4) { // deselect an area from the current selection 
    list($x, $y, $x2, $y2) = func_get_args(); 
    imagecopymerge($this->copy->img, $this->img, $x, $y, $x, $y, $x2-$x, $y2-$y, 100); 
    }else{ // deselect everything, draw the perforated copy back over the original 
    imagealphablending($this->img, true); 
    imagecopymerge($this->img, $this->copy->img, 0, 0, 0, 0, $this->x, $this->y, 100); // copy the copy back 
    $this->copy->__destruct(); 
    $this->selected = false; 
    } 
} 

对于那些好奇,这里有两类:

http://dev.expocom.nl/functions.php?id=104 (image.class.php) 
http://dev.expocom.nl/functions.php?id=171 (MyImage.class.php extends image.class.php)