php图像调整大小-从中心平方/裁剪缩略图?

标签 php image resize thumbnails crop

我有一个图像上传脚本,可将上传图像的大小调整为 150x150 像素。如果图像是方形的,那就太好了,但如果有人上传 640x200 像素的图像,它看起来就不漂亮了。

所以我基本上需要它根据图像的中心自动创建一个方形缩略图。如果图像较宽,则应裁剪掉左侧和右侧。如果图像较高,则应裁剪掉顶部和底部。

我在网上找到了一个代码修改,准确的说是这里:

Upload, resize, and crop center of image with PHP

我不太擅长 PHP,我已经在这方面花了几个小时了,试图将下面的代码与上面的选项结合起来。如果有人能帮助我那就太好了:)

                                $target_path = "avatars/";
        $image     = $_FILES['uploadedfile']['name'];
        $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
        $_POST["userpic"]=$_FILES['uploadedfile']['name'];
        if($_FILES['uploadedfile']['tmp_name']!="") {
        $imagetype=explode(".",$_POST["userpic"]);

        if($imagetype[1]=="jpg" || $imagetype[1]=="JPG" || $imagetype[1]=="gif" || $imagetype[1]=="GIF")
        {
        $target_path = "avatars/";
        $thaid=$_POST["user_id"];
        $target_path = $target_path .$thaid.".".$imagetype[1]; 
        $target_path2 =$thaid.".".$imagetype[1]; 
        move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
        $_POST["userpic"]=$target_path2;
        $n_width=$setts['avatar_width']; 
        $n_height=$setts['avatar_height']; 
        $tsrc=$target_path; 
        $add=$target_path;

        if($imagetype[1]=="jpg" || $imagetype[1]=="JPG")
        {
        $im=imagecreatefromjpeg($add);
        $width=imagesx($im); 
        $height=imagesy($im); 
        $newimage=imagecreatetruecolor($n_width,$n_height);


        $ar = 1.00;

    if ($ar < 1) { // "tall" crop
$cropWidth = min($height * $ar, $width);
$cropHeight = $cropWidth / $ar;
    }
    else { // "wide" crop
$cropHeight = min($width / $ar, $height);
$cropWidth = $cropHeight * $ar;
    }


        imagecopyresized($newimage,$im,0,0,0,0,$n_width,$n_height,$cropWidth,$cropHeight);
        imagejpeg($newimage,$tsrc,100);
        }
        if($imagetype[1]=="gif" || $imagetype[1]=="GIF")
        {
        $im=imagecreatefromgif($add);
        $width=imagesx($im);              
        $height=imagesy($im);            
        $newimage=imagecreatetruecolor($n_width,$n_height);
        imagecopyresized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
        imagegif($newimage,$tsrc,100);
        }
        }
        else
        {
        $_POST["userpic"]="noimage.jpg";
        }
        } 

最佳答案

如果您安装了 ImageMagick,您可以执行以下操作:

<?php
$i = new Imagick();
$i->readImage($file);
$i->cropThumbnailImage($w,$h);

这样,您实际上不必担心数学。

关于php图像调整大小-从中心平方/裁剪缩略图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9410111/

相关文章:

php - 破坏 "submit"按钮的功能

php - 在 PDO 中绑定(bind) "not null"?

css - 图像在确定高度的中心位置

java - Freemarker 在 ftl 上嵌入图像

php - 如果客户/付款方发生意外,如何保存在线交易数据?

php - 在没有 codeigniter 的情况下测试数据库连接,可以做到吗?

c# - 如何在尝试加载之前检查 jpeg 图像文件是否实际上是有效图像?

css - 如何同时调整图像和表格的大小?

javascript - 使用 jQuery 监听浏览器宽度/高度变化

jquery - Jquery 调整图像大小