PHP图像上传,然后转换为jpg格式

时间:2015-08-01 12:02:13

标签: php image forms jpeg

所以我有一个网站,允许用户通过上传图像来更改网站上的个人资料图片。我已经整理了文件名的上传和更改。但我需要将上传的所有图像转换为jpg格式。这是可能的,我试着看一些其他的例子,但我无法理解它们。如果有人可以提供一些代码添加到这个或任何其他类型的帮助,我将非常感激。

注意:我今年14岁,只掌握基本知识。

再次感谢你。

PHP代码“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.";
        }
    }
    ?>

2 个答案:

答案 0 :(得分:0)

试试这段代码

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

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

答案 1 :(得分:0)

应该在服务器上安装Image magic。对于此命令

$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);