【问题标题】:black background is coming for transparent images while creating image in php [duplicate]在php中创建图像时,透明图像出现黑色背景[重复]
【发布时间】:2014-03-19 17:35:51
【问题描述】:

我正在使用以下代码在 php 中编写水印代码,但对于透明图像,黑色背景即将到来:

$font_path                = $_SERVER['DOCUMENT_ROOT'] . "/fonts/arial.ttf"; // Font file
$water_mark_text_2        = "IndustrialStores.com"; // Watermark Text
list($owidth,$oheight)    = getimagesize($oldimage_name);

$width    = $owidth;
$height   = $oheight; 
$image    = imagecreatetruecolor($width, $height);

$extension = pathinfo($oldimage_name, PATHINFO_EXTENSION);
$extension = strtolower($extension);

if($extension=="jpg" || $extension=="jpeg" ){
    $image_src = imagecreatefromjpeg($oldimage_name);
}
else if($extension=="png"){
    $image_src = imagecreatefrompng($oldimage_name);
}
else if($extension=="gif"){
    $image_src = imagecreatefromgif($oldimage_name);
}
else if($extension=="bmp"){
    $image_src = imagecreatefrombmp($oldimage_name);
}
else{
    copy($oldimage_name, $new_image_name);    
    unlink($oldimage_name);
    return true;
}

imagecopyresampled($image, $image_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
$blue = imagecolorallocate ($image, 179, 179, 179);
$bbox = imageftbbox($width/15, 0, $font_path, 'IndustrialStores.com');

$x = $bbox[0] + (imagesx($image) / 2) - ($bbox[4] / 2);
$y = $bbox[1] + (imagesy($image) / 2) - ($bbox[5] / 2) - 5;

imagettftext($image, $width/15, 0, $x, $y, $blue, $font_path, $water_mark_text_2);
imagejpeg($image, $new_image_name, 100);
imagedestroy($image);
unlink($oldimage_name);

我已经尝试过很多其他的 * 答案,比如使用:

$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

但这一切都没有用

【问题讨论】:

  • 我已经尝试过这个答案,但它不起作用

标签: php image-processing


【解决方案1】:

添加这些行会有帮助吗?

else{
    copy($oldimage_name, $new_image_name);    
    unlink($oldimage_name);
    return true;
}

// add these lines here!
imagealphablending($image, false);
imagesavealpha($image, true);

imagecopyresampled($image, $image_src, 0, 0, 0, 0, $width, $height, $owidth, $oheight);
$blue = imagecolorallocate ($image, 179, 179, 179);

【讨论】:

  • 已经试过了但没用或者你能告诉我在我的代码中我需要把这些行放在哪里
  • 针对代码上下文进行了编辑。
  • 我在这里尝试了这些行,但这会改变水印文本的颜色,但对背景没有影响仍然是黑色检查这个screencast.com/t/2XcvX0Gvjfbq
最近更新 更多