3

第一个问题,请温柔;-)

我编写了一个图像类,它使简单的事情(矩形、文本)更容易一些,基本上是 PHP 图像函数的一堆包装器方法。
我现在要做的是允许用户定义一个选择,并且让以下图像操作只影响所选区域。我想我会通过将图像复制到 imgTwo 并从中删除所选区域来做到这一点,像往常一样对原始图像执行以下图像操作,然后在调用 $img->deselect() 时,将 imgTwo 复制回原始图像,并销毁副本。

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

然后,我从副本中删除选择的方式是绘制一个透明颜色的矩形,这是有效的 - 但我无法弄清楚如何选择该颜色,同时确保它不会出现在其余部分的图像。此应用程序中的输入图像是真彩色 PNG,因此没有带有颜色索引的调色板(我认为?)。

  • 必须有一种更好的方法,而不是收集每个单独像素的颜色,然后找到 $existing_colours 数组中没有出现的颜色.. 对吗?
4

2 回答 2

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);
于 2009-06-26T12:41:48.677 回答
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)
于 2009-06-28T10:12:19.387 回答