簡體   English   中英

PHP調整大小圖像給出黑色背景

[英]PHP Resize image gives black background

我正在使用此代碼來調整大小:

  <?php
// Function for resizing any jpg, gif, or png image files
function ak_img_resize($target, $newcopy, $w, $h, $ext) {
    list($w_orig, $h_orig) = getimagesize($target);
    $scale_ratio = $w_orig / $h_orig;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;
    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    if ($ext == "gif"){ 
      $img = imagecreatefromgif($target);
    } else if($ext =="png"){ 
      $img = imagecreatefrompng($target);
    } else { 
      $img = imagecreatefromjpeg($target);
    }
    $tci = imagecreatetruecolor($w, $h);
    // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
    imagejpeg($tci, $newcopy, 80);
}
?>

但是每次我上傳透明的png圖像時,結果都是黑色背景。 如何防止這種情況發生並保持透明的背景?

在重新進行imagecopy采樣之前嘗試此操作,添加alpha混合,然后保存alpa

imagealphablending($tci, false);
imagesavealpha($tci,true);
$transparent = imagecolorallocatealpha($tci, 255, 255, 255, 127);
imagefilledrectangle($tci, 0, 0, $w, $h, $transparent);

試試這個,使您的調整大小功能

<?php
    $file_name =testimg.jpg // your file name
    extension= explode(".", strtolower($file_name));//get ext of your image

    if($extension[1]=="jpg" || $extension[1]=="jpeg" )
    {
        $src = imagecreatefromjpeg($filename); // Check ext and set src 
    }
    else if($extension[2]=="png")
    {
        $src = imagecreatefrompng($filename); // Check ext and set src 
    }
    else 
    {
        $src = imagecreatefromgif($filename); // Check ext and set src 
    } 
    list($width,$height)=getimagesize($filename);
    $newwidth=round($width/10);   //resized image width
    $newheight=round($height/10);  //resized image height
    $tmp=imagecreatetruecolor($newwidth,$newheight);
    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
    $resizedfile = "resizeduploads/". $name;
    if($extension[1]=="jpg" || $extension[1]=="jpeg" )
    {
        imagejpeg($tmp,$resizedfile);
    }
    else if($extension[1]=="png")
    {
        imagepng($tmp,$resizedfile);
    }
    else 
    {
        imagegif($tmp,$resizedfile);
    }
    imagedestroy($src);
    imagedestroy($tmp);

嘗試使用imagecolortransparent設置透明顏色:

http://il.php.net/manual/zh/function.imagecolortransparent.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM