我正在使用此功能在图像的左上角添加水印,jpeg或png。
我需要Switch和Case来区分png和jpeg以分别处理每种图像类型。
每次运行该功能时,图像都经过完美编辑,但是调试显示图像正在处理为.png和.jpg,因此在图像类型错误时会出现问题。
function addWatermark($path)
{
$public_file_path = dirname(__FILE__);
$font = $public_file_path . '/src/fonts/Roboto-Light.ttf';
// get fiel type for switch
$size = getimagesize($path);
// get $from name
$path_parts = pathinfo($path);
$text= $path_parts['filename'];
switch($path_parts['extension'])
{
case "jpeg" or "jpg":
// Copy and resample the imag
list($width, $height) = getimagesize($path);
$image_p = imagecreatefromjpeg($path);
// Prepare font size and colors
$text_color = imagecolorallocate($image_p, 0, 0, 0);
$bg_color = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 17;
// Set the offset x and y for the text position
$offset_x = 0;
$offset_y = 20;
// Get the size of the text area
$dims = imagettfbbox($font_size, 0, $font, $text);
$text_width = $dims[4] - $dims[6] + $offset_x;
$text_height = $dims[3] - $dims[5] + $offset_y;
// Add text background
imagefilledrectangle($image_p, 0, 0, $text_width, $text_height, $bg_color);
// Add text
imagettftext($image_p, $font_size, 0, $offset_x, $offset_y, $text_color, $font, $text);
// Save the picture
imagejpeg($image_p, $path, 90);
// Clear
imagedestroy($image_p);
case "png":
$im = imagecreatefrompng($path);
imagesavealpha($im, true); // important to keep the png's transparency
$text_color = imagecolorallocate($im, 0, 0, 0);
$width = imagesx($im); // the width of the image
$height = imagesy($im);; // the heighst of the image
$font_size = 15; // font size
$box_color = imagecolorallocate($im, 255, 255, 255);
// Set the offset x and y for the text position
$offset_x = 0;
$offset_y = 20;
$dims = imagettfbbox($font_size, 0, $font, $text);
$text_width = $dims[4] - $dims[6] + $offset_x;
$text_height = $dims[3] - $dims[5] + $offset_y;
// Add text background
imagefilledrectangle($im, 0, 0, $text_width, $text_height, $box_color);
// Add text
imagettftext($im, $font_size, 0, $offset_x, $offset_y, $text_color, $font,$text);
imagepng($im, $path, 0);
imagedestroy($im);
case "mp4";
break;
}
// hasta aca
}
答案 0 :(得分:4)
我不相信你可以在案例陈述中使用or
。在此示例中,所有内容都与第一种情况匹配:http://sandbox.onlinephpfunctions.com/code/8edfd01d386e9f7bb56975b9b1ecb9dee4669494
您的代码应为:
switch($path_parts['extension'])
{
case "jpeg":
case "jpg":
// Your code
break;
case "png":
// Your code
break;
case "mp4";
break;
}
答案 1 :(得分:1)
您需要在案例陈述中添加break;
。
switch($path_parts['extension'])
{
case "jpeg":
case "jpg":
// Your code
break;
case "png":
// Your code
break;
case "mp4";
break;
}
答案 2 :(得分:0)
所以看起来你可能会遗漏破坏声明,我不确定是否可以使用case('jpg')或case('jpeg')。您可以使用此替代方法:
switch(var) {
case('jpg'):
case('jpeg'):
break;
case('png'):
break;
default:
break;
}