上传PHP时调整图像大小

时间:2015-08-12 14:10:06

标签: php image

我正在使用以下格式上传图片:

include 'extraphp/config.php';

$title = $_POST['titleStory'];
$excerpt = $_POST['excerptStory'];
$story = $_POST['storyStory'];
$catagory = $_POST['catagory'];
$tags = $_POST['tagsStory'];
$author = $_POST['authorStory'];
$date = $_POST['dateStory'];

/* Image Upload */

$image = $_FILES["imageStory"];
$image2= preg_replace("/[^A-Z0-9._-]/i", "_", $image["name"]);

$target_dir = "../uploads/large/";
$target_file = $target_dir . $image2;
move_uploaded_file($_FILES['imageStory']['tmp_name'], $target_file);

$catagory2 = implode (", ", $catagory);
$author2 = implode(',', $author);

$sql="INSERT INTO story (titleStory,excerptStory,storyStory,catagory,tagsStory,authorStory,dateStory,imageStory) VALUES ('". $title ."','". $excerpt ."','". $story ."','". $catagory2 ."','". $tags ."','". $author2 ."','". $date ."','". $target_file ."')";

mysqli_query($con,$sql);
header("location: dashboard.php")

现在我想将此图像调整为180px X 109px 有人帮我吗?

1 个答案:

答案 0 :(得分:2)

请记住,您需要检查图片扩展名才能使用corret imagecreate...功能。该示例使用始终imagecreatefromjpeg(),假设所有上传的图像都是JPG。

list( $imageWidth, $imageHeight ) = getimagesize( $target_file );

$resampledImage = imagecreatetruecolor( 180, 109 );

//Check file extension here to use the correct image create function
//imagecreatefromjpeg(); imagecreatefrompng(); imagecreatefromgif() etc...
$source = imagecreatefromjpeg( $target_file );

imagecopyresized( $resampledImage, $source, 180, 109, $imageWidth, $imageHeight );

ob_start();

//Check file extension here to use the correct image output function
//imagejpeg(); imagegif(); imagepng() etc...
imagejpeg( $resampledImage, null, 100 );

$imageContent = ob_get_clean();

file_put_contents( $target_file, $imageContent );

http://php.net/manual/en/function.getimagesize.php

http://php.net/manual/en/function.imagecreatetruecolor.php

http://php.net/manual/en/function.imagecreatefromjpeg.php

http://php.net/manual/en/function.imagecreatefrompng.php

http://php.net/manual/en/function.imagecopyresized.php

http://php.net/manual/en/function.imagejpeg.php

http://php.net/manual/en/function.ob-start.php

http://php.net/manual/en/function.file-put-contents.php