【问题标题】:PHP - Image resizing issue when uploadedPHP - 上传时图像大小调整问题
【发布时间】:2014-08-17 22:31:47
【问题描述】:

我很难让我的网络应用程序正常工作。我一直在努力让我的头像不会被推送,并在上传时自动调整大小。我对 PHP 不是最好的,因此为什么我不能自己做到这一点。如果有人可以帮助我,我将不胜感激。那是头像文件的代码。

最好的问候!

if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {

                $name           = $_FILES['myfile']['name'];
                $tmp_name       = $_FILES['myfile']['tmp_name'];
                $allowed_ext    = array('jpg', 'jpeg', 'png', 'gif' );
                $a              = explode('.', $name);
                $file_ext       = strtolower(end($a)); unset($a);
                $file_size      = $_FILES['myfile']['size'];        
                $path           = "avatars";

                if (in_array($file_ext, $allowed_ext) === false) {
                    $errors[] = 'Image file type not allowed';  
                }

                if ($file_size > 2097152) {
                    $errors[] = 'File size must be under 2mb';
                }

            } else {
                $newpath = $user['image_location'];
            }

【问题讨论】:

    标签: php resize avatar


    【解决方案1】:

    您需要将上传的图片存储在您的网络服务器上

    为此:

    你需要:

    move_uploaded_file()

    为了调整大小,您可以使用:

    imagecopyresampled()

    如下:

    function resizeIMG($o_img // original image
    , $target_image // Resized New Image
    , $newWidth, $newHeight){
    // Get Original Dimensions as follows:
    $original_width=imagesx($o_image); //Returns width of image
    $original_height=imagesy($o_image); //Returns height of image
    $tmp = imagecreatetruecolor($newWidth, $newHeight); // Create New temp. image with new dimensions
    imagecopyresampled($tmp_img, $o_img, 0, 0, 0, 0, $newWidth, $newHeight, $original_width, $original_height); // Resize original image to temporary Image
    imagejpeg($tmp, $target_image, $quality); // Copy temp Image to Target File for JPG images
    imagedestroy($tmp); // Destroy Temporary Image.
    /* Use
    imagepng() instead of imagejpeg() for PNG images
    imagegif() instead of imagejpeg() for GIF images
    */
    }
    

    对于提到的所有这些功能,您需要为您的 php.ini 启用 gd_drivers。如果您使用的是 Windows,只需在行 extension=php_gd2.dll 之前删除 ; 或查看 this 对于其他人。

    或者你可以在 php 中使用image_magick

    也可以看看:Resize images in PHP without using third-party libraries?

    希望它有所帮助.. 干杯:)。

    【讨论】:

      猜你喜欢
      • 2014-01-09
      • 2013-09-19
      • 1970-01-01
      • 2014-03-14
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多