繁体   English   中英

在上传之前进行转换,然后在服务器png / gif上保存为jpg

[英]converting DURING upload before saving on server png/gif to jpg

所以我有一个图像上传脚本。 它将上载图像并将其保存到服务器上的空间。 我似乎无法理解的是,当用户上传.png时,当它保存在我的服务器上时,我希望它成为jpg。

任何人都可以提供帮助,请不要直接将我引向另一个问题,因为我还没有任何工作。 这是我的代码示例。

$name = addslashes($_FILES['image']['name']);
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION); 
$size = $_FILES['image']['size'];
$temp = $_FILES ['image']['tmp_name'];
$error = $_FILES ['image']['error'];

if ($error > 0)
    die("Error uploading file! Code $error.");
else


if ($password == "" || $size > 2000000) {
    move_uploaded_file($temp, $images.$name);   
    mysql_query("INSERT INTO image_approval VALUES ('','$description','','$images$name','',NOW())");

    echo "Upload complete!";
    }else{
echo "Error uploading file";
    }

使用GD ,并假设$images是存储$images的目录(以斜杠结尾),而$name name-原始图像的文件名:

$destinationPath = $images . basename($name, $ext) . '.jpg';
$source = imagecreatefrompng($images . $name);
imagejpeg($source, $destinationPath, 75);
imagedestroy($source);

或使用Imagick

$image = new Imagick($images . $name);
$image->writeImage($destinationPath);
$image->destroy();

使用此功能转换上传的图像

// http://stackoverflow.com/a/1201823/358906
// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

然后使用unlink()删除旧图像。

您的代码将类似于:

// After the upload
png2jpg($the_jpg_file_path, $the_png_file_path, 80);
unlink($the_jpg_file_path);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM