PHP 對 透明背景的圖片 要做縮圖, 要如何做? (限 png 和 gif)
- 註1: 透明背景、透明底圖的圖片, 沒特別處理, 會變成一片黑.
- 註2: 要等比例縮圖, 請搭配此篇程式做修改: PHP 等比例縮圖程式 (下述程式參數同此文, 就不多加解釋)
PHP 對 透明背景的圖片 做縮圖
透明背景處理主要要靠下述幾行:
<?php // imagealphablending($image_new, false); imagesavealpha($image_new, true); $color = imagecolorallocatealpha($image_new, 0, 0, 0, 127); imagefill($image_new, 0, 0, $color); ?>
這邊直接把範例程式寫出來, 直接使用即可.
<?php function image_resize_transparent($from_filename, $save_filename, $new_width = 400, $new_height = 300) { // 透明背景只有 png 和 gif 支援 $allow_format = array('png', 'gif'); $sub_name = $t = ''; // Get new dimensions $img_info = getimagesize($from_filename); $width = $img_info['0']; $height = $img_info['1']; $mime = $img_info['mime']; list($t, $sub_name) = explode('/', $mime); if (!in_array($sub_name, $allow_format)) return false; // Resample $image_new = imagecreatetruecolor($new_width, $new_height); // $function_name: set function name // => imagecreatefrompng, imagecreatefromgif // $sub_name = png, gif $function_name = 'imagecreatefrom' . $sub_name; $image = $function_name($from_filename); //$image = imagecreatefrompng($from_filename); // 透明背景 // imagealphablending($image_new, false); imagesavealpha($image_new, true); $color = imagecolorallocatealpha($image_new, 0, 0, 0, 127); imagefill($image_new, 0, 0, $color); imagecopyresampled($image_new, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // return imagepng($image_new, $save_filename); $function_name = 'image' . $sub_name; return $function_name($image_new, $save_function); } ?>
使用範例: image_resize_transparent('logo.png', 'logo_200x150.png', 200, 150);