php GD添加填充到图像

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php GD添加填充到图像脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Web上找到了关于图像处理的一些关于 PHP GD的东西,但是没有一个似乎给了我正在寻找的东西.

我有上传任何尺寸的图像,我写的脚本将图像的大小调整到不超过200像素乘以200像素高,同时保持宽高比.所以最终的图像可以是150px×200px.然后,我想做的是进一步操作图像,并在图像周围添加一个垫子,将其贴到200像素乘200像素,而不影响原始图像.例如:

我必须将图像调整大小的代码在这里,我已经尝试了几件事情,但是肯定有一个问题来实现添加填充的辅助过程.

list($imagewidth,$imageheight,$imageTyPE) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
swITch($imageType) {
    case "image/gif":
        $source=imagecreatefromgif($image); 
        break;
    case "image/pjpeg":
    case "image/jpeg":
    case "image/jpg":
        $source=imagecreateFromjpeg($image); 
        break;
    case "image/png":
    case "image/x-png":
        $source=imagecreatefrompng($image); 
        break;
}
imagecopyresampled($newImage,$source,$newImageWidth,$newImageHeight,$width,$height);
imagejpeg($newImage,$image,80);
chmod($image,0777);

我想我需要在imagecopyresampled()调用之后使用imagecopy().这样,图像已经是我想要的尺寸,我只需要创建一个200 x 200的图像,并将$newImage粘贴到中心(vert和horiz)中.我需要创建一个全新的图像并合并两者,还是有一种方法来填补我已经创建的图像($newImage)?提前感谢,我发现的所有教程都导致我无处可寻,而在SO中发现的唯一适用的是andROId:

>打开原始图像
>创建一个新的空白图像.
>用您想要的背景颜色填充新图像
>使用ImageCopyResampled调整大小并复制以新图像为中心的原始图像
>保存新图像

您也可以使用switch语句

$img = imagecreatefromstring( file_get_contents ("path/to/image") );

这将自动检测图像类型(如果您的安装支持imagetype)

更新了代码示例

$orig_filename = 'c:\temp\380x253.jpg';
$new_filename = 'c:\temp\test.jpg';

list($orig_w,$orig_h) = getimagesize($orig_filename);

$orig_img = imagecreatefromstring(file_get_contents($orig_filename));

$output_w = 200;
$output_h = 200;

// determine scale based on the longest Edge
if ($orig_h > $orig_w) {
    $scale = $output_h/$orig_h;
} else {
    $scale = $output_w/$orig_w;
}

    // calc new image dimensions
$new_w =  $orig_w * $scale;
$new_h =  $orig_h * $scale;

echo "Scale: $scale<br />";
echo "New W: $new_w<br />";
echo "New H: $new_h<br />";

// determine offset coords so that new image is centered
$offest_x = ($output_w - $new_w) / 2;
$offest_y = ($output_h - $new_h) / 2;

    // create new image and fill with background colour
$new_img = imagecreatetruecolor($output_w,$output_h);
$bgcolor = imagecolorallocate($new_img,255,0); // red
imagefill($new_img,$bgcolor); // fill background colour

    // copy and resize original image into center of new image
imagecopyresampled($new_img,$orig_img,$offest_x,$offest_y,$new_w,$new_h,$orig_w,$orig_h);

    //save it
imagejpeg($new_img,$new_filename,80);

脚本宝典总结

以上是脚本宝典为你收集整理的php GD添加填充到图像全部内容,希望文章能够帮你解决php GD添加填充到图像所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。