2008-11-10 109 views
35

我試圖在PHP中調整帶有透明背景的png,我在網上找到的代碼示例對我來說不起作用。這裏是我使用的代碼,建議將非常感謝!如何在PHP中使用透明度調整png的大小?

$this->image = imagecreatefrompng($filename); 

imagesavealpha($this->image, true); 
$newImage = imagecreatetruecolor($width, $height); 

// Make a new transparent image and turn off alpha blending to keep the alpha channel 
$background = imagecolorallocatealpha($newImage, 255, 255, 255, 127); 
imagecolortransparent($newImage, $background); 
imagealphablending($newImage, false); 
imagesavealpha($newImage, true); 

imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); 
$this->image = $newImage; 
imagepng($this->image,$filename); 


更新 通過「不工作」我的意思是說背景色更改爲黑色,當我調整PNG格式。

+0

你是什麼意思的例子不適合你? – 2008-11-10 21:37:51

回答

68

從我可以告訴,你需要將混合模式設置爲false,以及alpha通道標誌保存到true之前你做的imagecolorallocatealpha()

<?php 
$newImg = imagecreatetruecolor($nWidth, $nHeight); 
imagealphablending($newImg, false); 
imagesavealpha($newImg,true); 
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); 
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent); 
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, 
         $imgInfo[0], $imgInfo[1]); 
?> 

UPDATE:此代碼只在透明背景下工作,不透明度= 0.如果你的圖像有0 <不透明度< 100它會是黑色背景。

+3

這對我來說不起作用,仍然黑色背景。 – 2008-11-13 00:13:17

+0

答案是完全不相關的,但這是用透明度調整大小的正確方法。 – 2009-11-30 16:28:57

+0

這絕對是創建/複製透明PNG圖像的正確方法。 – tftd 2011-11-30 22:09:45

4

用透明色填充新圖像也是必需的(如Dycey編碼,但我猜忘了提及:)),而不僅僅是「戰略」節省本身。

IIRC,您還需要確定PNG是24位,即truecolor,而不是8位,以避免出現錯誤行爲。

4

舊的線程,但以防萬一 - Dycey的例子應該工作,如果你正確地命名的東西。這是我的圖像調整大小類中使用的修改版本。注意檢查,以確保imagecolorallocatealpha()的定義,而如果你使用的GD < 2.0.8

/** 
    * usually when people use PNGs, it's because they need alpha channel 
    * support (that means transparency kids). So here we jump through some 
    * hoops to create a big transparent rectangle which the resampled image 
    * will be copied on top of. This will prevent GD from using its default 
    * background, which is black, and almost never correct. Why GD doesn't do 
    * this automatically, is a good question. 
    * 
    * @param $w int width of target image 
    * @param $h int height of target image 
    * @return void 
    * @private 
    */ 
    function _preallocate_transparency($w, $h) { 
     if (!empty($this->filetype) && !empty($this->new_img) && $this->filetype == 'image/png')) { 
      if (function_exists('imagecolorallocatealpha')) { 
       imagealphablending($this->new_img, false); 
       imagesavealpha($this->new_img, true); 
       $transparent = imagecolorallocatealpha($this->new_img, 255, 255, 255, 127); 
       imagefilledrectangle($this->new_img, 0, 0, $tw, $th, $transparent); 
      } 
     } 
    } 
2

這也是不是爲我工作:( THISIS我的解決方案也不會..但我也得到一個黑色的背景和圖片不是透明

<?php 
$img_id = 153; 

$source = "images/".$img_id.".png"; 
$source = imagecreatefrompng($source); 
$o_w = imagesx($source); 
$o_h = imagesy($source); 

$w = 200; 
$h = 200; 

$newImg = imagecreatetruecolor($w, $h); 
imagealphablending($newImg, false); 
imagesavealpha($newImg,true); 
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); 
imagefilledrectangle($newImg, 0, 0, $w, $h, $transparent); 
imagecopyresampled($newImg, $source, 0, 0, 0, 0, $w, $h, $o_w, $o_h); 

imagepng($newImg, $img_id.".png"); 

?> 
<img src="<?php echo $img_id.".png" ?>" /> 
1

完整的示例。請注意,互聯網它的工作原理不正確上發現了一些PNG圖像,但對於我自己用Photoshop創建它工作正常。

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

$filename = "url to some image"; 

$newWidth = 300; 
$newHeight = 300; 

$imageInfo = getimagesize($filename); 

$image = imagecreatefrompng($filename); //create source image resource 
imagesavealpha($image, true); //saving transparency 

$newImg = imagecreatetruecolor($newWidth, $newHeight); //creating conteiner for new image 
imagealphablending($newImg, false); 
imagesavealpha($newImg,true); 
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); //seting transparent background 
imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent); 
imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $imageInfo[0], $imageInfo[1]); 

imagepng($newImg); //printout image string 
8

這是一個對我來說很好的最終解決方案。

function resizePng($im, $dst_width, $dst_height) { 
    $width = imagesx($im); 
    $height = imagesy($im); 

    $newImg = imagecreatetruecolor($dst_width, $dst_height); 

    imagealphablending($newImg, false); 
    imagesavealpha($newImg, true); 
    $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); 
    imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent); 
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $dst_width, $dst_height, $width, $height); 

    return $newImg; 
} 
3

它可能涉及到PHP的新版本(我用PHP 5.6測試),但現在這個工作,而不需要使用透明背景,以填補圖像:

$image_p = imagecreatetruecolor(480, 270); 
imageAlphaBlending($image_p, false); 
imageSaveAlpha($image_p, true); 
$image = imagecreatefrompng('image_with_some_transaprency.png'); 
imagecopyresampled($image_p, $image, 0, 0, 0, 0, 480, 270, 1920, 1080); 
imagepng($image_p, 'resized.png', 0); 
0

下面是完整的代碼爲保存圖像透明度的PNG文件工作..

list($width, $height) = getimagesize($filepath); 
$new_width = "300"; 
$new_height = "100"; 

if($width>$new_width && $height>$new_height) 
{ 
    $image_p = imagecreatetruecolor($new_width, $new_height); 
    imagealphablending($image_p, false); 
    imagesavealpha($image_p, true); 
    $image = imagecreatefrompng($filepath); 
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
    imagepng($image_p,$filepath,5); 
} 
0

也沒有上述解決方案爲我工作。這是我發現解決問題的方式。

// upload directory 
$upload_dir = "../uploads/"; 
// valid image formats 
$valid_formats = array("jpg", "jpeg", "png"); 
// maximum image size 1 mb 
$max_size = 1048576; 
// crop image width, height 
$nw = $nh = 800; 
$nw1 = $nh1 = 400; 
$nw3 = $nh3 = 200; 
$nw2 = $nh2 = 100; 
// checks that if upload_dir a directory/not 
if (is_dir($upload_dir) && is_writeable($upload_dir)) { 
    // not empty file 
    if (!empty($_FILES['image'])) { 
     // assign file name 
     $name = $_FILES['image']['name']; 
     // $_FILES to execute all files within a loop 
     if ($_FILES['image']['error'] == 4) { 
      $message = "Empty FIle"; 
     } 
     if ($_FILES['image']['error'] == 0) { 
      if ($_FILES['image']['size'] > $max_size) { 
       echo "E-Image is too large!<br>"; 
       $_SESSION['alert'] = "Image is too large!!"; 
      } else if (!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)) { 
       $_SESSION['alert'] = "This image is not a valid image format!!"; 
       echo "E-This image is not a valid image format<br>"; 
      } else if (file_exists($upload_dir . $name)) { 
       $_SESSION['alert'] = "Image already exists!!"; 
       echo "E-Image already exists<br>"; 
      } else { // No error found! Move uploaded files 
       $size = getimagesize($_FILES['image']['tmp_name']); 
       $x = (int) $_POST['x']; 
       $y = (int) $_POST['y']; 
       $w = (int) $_POST['w'] ? $_POST['w'] : $size[0]; 
       $h = (int) $_POST['h'] ? $_POST['h'] : $size[1]; 
       // path for big image 
       $big_image_path = $upload_dir . "big/" . $name; 
       // medium image path 
       $medium_image_path = $upload_dir . "medium/" . $name; 
       // small image path 
       $small_image_path = $upload_dir . "small/" . $name; 
       // check permission 
       if (!is_dir($upload_dir . "big/") && !is_writeable($upload_dir . "big/")) { 
        mkdir($upload_dir . "big/", 0777, false); 
       } 
       if (!is_dir($upload_dir . "medium/") && !is_writeable($upload_dir . "medium/")) { 
        mkdir($upload_dir . "medium/", 0777, false); 
       } 
       if (!is_dir($upload_dir . "small/") && !is_writeable($upload_dir . "small/")) { 
        mkdir($upload_dir . "small/", 0777, false); 
       } 
       // image raw data from form 
       $data = file_get_contents($_FILES["image"]["tmp_name"]); 
       // create image 
       $vImg = imagecreatefromstring($data); 
       //create big image 
       $dstImg = imagecreatetruecolor($nw, $nh); 
       imagealphablending($dstImg, false); 
       $trans_colour = imagecolorallocatealpha($dstImg, 0, 0, 0, 127); 
       imagefilledrectangle($dstImg, 0, 0, $w, $h, $trans_colour); 
       imagesavealpha($dstImg, true); 
       imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h); 
       imagepng($dstImg, $big_image_path); 
       //create medium thumb 
       $dstImg1 = imagecreatetruecolor($nw1, $nh1); 
       imagealphablending($dstImg1, false); 
       $trans_colour1 = imagecolorallocatealpha($dstImg1, 0, 0, 0, 127); 
       imagefilledrectangle($dstImg1, 0, 0, $w, $h, $trans_colour1); 
       imagesavealpha($dstImg1, true); 
       imagecopyresampled($dstImg1, $vImg, 0, 0, $x, $y, $nw1, $nh1, $w, $h); 
       imagepng($dstImg1, $medium_image_path); 
       // create smallest thumb 
       $dstImg2 = imagecreatetruecolor($nw2, $nh2); 
       imagealphablending($dstImg2, false); 
       $trans_colour2 = imagecolorallocatealpha($dstImg2, 0, 0, 0, 127); 
       imagefilledrectangle($dstImg2, 0, 0, $w, $h, $trans_colour2); 
       imagesavealpha($dstImg2, true); 
       imagecopyresampled($dstImg2, $vImg, 0, 0, $x, $y, $nw2, $nh2, $w, $h); 
       imagepng($dstImg2, $small_image_path); 
       /* 
       * Database insertion 
       */ 
       $sql = "INSERT INTO tbl_inksand_product_gallery (" 
         . "Product_Id,Gallery_Image_Big,Gallery_Image_Medium,Gallery_Image_Thumb," 
         . "Gallery_Status,Created_By,Created_Datetime" 
         . ") VALUES (" 
         . "'{$Product_Id}','{$big_image_path}','{$medium_image_path}','{$small_image_path}'," 
         . "'A','$Created_By','{$time}'" 
         . ")"; 
       db_query($sql); 
       if (db_affected_rows() == 1) { 
        if (imagedestroy($dstImg)) { 
         $_SESSION['success'] = "Image uploaded successfully."; 
         echo "S-Image uploaded successfully<br>"; 
        } else { 
         $_SESSION['alert'] = "Image not uploaded!!"; 
         echo "S-Image not uploaded"; 
        } 
       } else { 
        $_SESSION['alert'] = "Error in uploading image!!"; 
        echo "E-Error in uploading image!!"; 
       } 
      } 
     } 
    } 
} else { 
    mkdir($upload_dir, 0777); 
} 
相關問題