【问题标题】:PHP Image upload which then converts into jpg formatPHP 图片上传,然后转换为 jpg 格式
【发布时间】:2015-10-24 01:04:30
【问题描述】:

所以我有一个网站,允许用户通过上传图片来更改网站上的个人资料图片。我已经整理好文件名的上传和更改。但我需要将所有上传的图像转换为 jpg 格式。这可能吗,我尝试查看其他一些示例,但我无法理解它们。如果有人可以为此提供一些附加代码或任何其他帮助,我将不胜感激。

注意:我今年 14 岁,只有 php 的基本知识。

再次感谢您。

PHP CODE“upload.php”(表单提交图片后打开)

<?php
    $target_dir = "uploads/";
    $newFileName = $target_dir .'YourfileName'.'.'. pathinfo($_FILES["fileToUpload"]["name"] ,PATHINFO_EXTENSION); //get the file extension and append it to the new file name
    $uploadOk = 1;
    $imageFileType = pathinfo($_FILES["fileToUpload"]["name"] ,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],  $newFileName)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    ?>

【问题讨论】:

标签: php image forms jpeg


【解决方案1】:

试试这个代码

$f = explode(".",$_FILES["fileToUpload"]["name"]);

$file = $f[0].".jpg";
$newFileName = $target_dir .$file;

【讨论】:

  • 第二行。大多数图像将接受 jpg 格式。
【解决方案2】:

图像魔术应该安装在服务器上。对于这个命令

$cmd = "convert path/to/image/imagename.extension  path/to/image/imagename.jpg";
exec($cmd);

在你的情况下,在 move_uploaded_file() 之后使用它

$cmd = "convert $newFileName ".$target_dir."YourfileName".".jpg' ;
exec($cmd);

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    相关资源
    最近更新 更多