2012-02-24 116 views
4

我的網站(以html和php整體編碼)包含一項功能,允許某些用戶上傳圖片。圖像被調整大小和使用此代碼加水印:用php爲水印圖片加水印

function watermarkpic($filename) { 

ini_set('max_input_time', 300); 

require 'config.php'; 

$watermark = imagecreatefrompng('watermarknew.png'); 
$watermarkwidth = imagesx($watermark); 
$watermarkheight = imagesy($watermark); 

if(preg_match('/[.](jpg)$/', $filename)) { 
     $originalimage = imagecreatefromjpeg($path_to_image_directory . $filename); 
    } else if (preg_match('/[.](gif)$/', $filename)) { 
     $originalimage = imagecreatefromgif($path_to_image_directory . $filename); 
    } else if (preg_match('/[.](png)$/', $filename)) { 
     $originalimage = imagecreatefrompng($path_to_image_directory . $filename); 
    } 

$originalwidth = imagesx($originalimage); 
$originalheight = imagesy($originalimage); 

$maxsize = 800; 
$imgratio = $originalwidth/$originalheight; 

if($imgratio > 1) { 
    $finalwidth = $maxsize; 
    $finalheight = $maxsize/$imgratio; 
} 
else { 
    $finalheight = $maxsize; 
    $finalwidth = $maxsize * $imgratio; 
} 

$finalimage = imagecreatetruecolor($finalwidth,$finalheight); 

imagecopyresampled($finalimage, $originalimage, 0,0,0,0,$finalwidth,$finalheight,$originalwidth,$originalheight); 

imagecopymerge($finalimage, $watermark, 0, 0, 0, 0, $watermarkwidth, $watermarkheight, 100); 

//now move the file where it needs to go 
if(!file_exists($path_to_medimage_directory)) { 
     if(!mkdir($path_to_medimage_directory)) { 
       die("There was a problem. Please try again!"); 
     } 
    } 

imagejpeg($finalimage, $path_to_medimage_directory . $filename); 
} 

的問題是,所述水印具有透明背景,但它顯示爲具有圖像在黑色背景上。我看過有關alpha混合等的東西,但我不知道這是什麼。我想了解我在做什麼,以及如何解決問題,使水印透明,因爲它應該是。真實的圖片應該填補空白。

在此先感謝。

+1

Jpegs不支持透明度 – 2012-02-24 15:59:59

回答

0

所以我想通了;而不是使用imagecopymerge()我用imagecopy()它工作得很好。

我看到某處可能存在一個與imagecopymerge()有關的錯誤,它導致了PHP5中的錯誤。

2

斯科特,有很多事情可以在這裏進行。

  1. 你需要確保你保存你的PNG使用沒有索引的alpha透明度。索引透明度基本上說「這種顏色(也許是黑色)將在整個圖像中顯示爲透明。」當被瀏覽器或圖像編輯器讀取時,它可能是透明的,但特別是如果您將它與JPG合併,透明度將不會被遵守。如果您想了解更多信息,請嘗試使用http://www.idux.com/2011/02/27/what-are-index-and-alpha-transparency/

  2. 確保您獲得了兩張圖像的正確尺寸。請參閱Transparent PNG over JPG in PHP以確保您沒有遇到同樣的問題。

  3. 如果你仍然遇到問題,你可能想在這裏檢查:http://php.net/manual/en/image.examples.merged-watermark.php,因爲它顯示瞭如何改變圖像的不透明度。它可能接近你想要完成的事情,或者可能會慢慢思考另一個想法。

+0

所以我想通了,而不是使用imagecopymerge我用圖像複製,它工作正常。我看到了某處,可能會有一個imagecopymerge的bug,導致這在php5中 – 2012-02-26 20:01:59

0

http://php.net/manual/en/function.imagecopymerge.php

<?php 
    $src = imagecreatefromstring(file_get_contents('watermark.png')); 
    $dest = imagecreatefromstring(file_get_contents('Unmarked/indian_elephant_chasing_bird.jpg')); 

    // Set the brush 
    imagesetbrush($dest, $src); 
    // Draw a couple of brushes, each overlaying each 
    imageline($dest, 
     imagesx($src)/2, 
     imagesy($src)/2, 
     imagesx($src)/2 , 
     imagesy($src)/2, 
     IMG_COLOR_BRUSHED); 

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