2009-06-26 114 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)