我想问一下如何从Opencart客户网站上传图片(例如个人资料图片)并调整大小?我的代码可以上传图片,但无法调整图片大小。如果我有文件5MB图像文件,我想将文件缩小到大约200KB。我已经尝试过PHP函数imagejpeg,但它不起作用,它不会上传图像。这是我的代码:
//Check the post
if((!empty($_FILES)) && ($_FILES['photo']['size'] > 0) && ($_FILES['photo']['error'] == 0)){
//check extension
$fileType = strtolower(pathinfo(basename($this->request->files['photo']['name']), PATHINFO_EXTENSION));
if($fileType != "jpeg" && $fileType != "jpg" && $fileType != "png" && $fileType != "bmp"){
echo "<script>
alert('Extension allowed : jpeg, jpg, png, dan bmp. Your extension: ".$fileType."');
window.location.href='javascript: window.history.go(-1)';
</script>";
die();
}
//check image size
if($this->request->files['photo']['size'] > 5000000){
echo "<script>
alert('File too big, max. 5000000 (5MB). Your file: ".$this->request->files['photo']['size']."');
window.location.href='javascript: window.history.go(-1)';
</script>";
die();
}
$fileName = $this->request->files['photo']['name'];
$newimg = date('YmdHis', time());
$arr = explode(".", $fileName);
$extension = strtolower(array_pop($arr));
$foto = $newimg.".".$extension;
$uploads_dir = 'image/data/profile/';
if (is_uploaded_file($this->request->files['photo']['tmp_name'])) {
//i want to shrink image size before this upload
move_uploaded_file($this->request->files['photo']['tmp_name'], $uploads_dir.$foto);
}
}
else{
echo "<script>
alert('Please choose a photo');
window.location.href='javascript: window.history.go(-1)';
</script>";
die();
$foto = '';
}
答案 0 :(得分:0)
您可以尝试使用以下代码段来减少图片上传期间的图片尺寸 -
<?php
function reduce_image_size($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
else if ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
else if ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}
if($_POST) {
if ($_FILES["file"]["error"] > 0) {
$output = $_FILES["file"]["error"];
} else if (($_FILES["file"]["type"] == "image/gif") ||
($_FILES["file"]["type"] == "image/jpeg") ||
($_FILES["file"]["type"] == "image/png") ||
($_FILES["file"]["type"] == "image/pjpeg")) {
$destination = 'reduced.jpg';
$filename = reduce_image_size($_FILES["file"]["tmp_name"], $destination, 80);
$output = 'Done.';
} else {
$output = "Uploaded image should be jpg or gif or png.";
}
echo $output . " <a href=''>Reload</a>"; die;
}
?>
<html>
<head>
<title>Reduce Image Size with PHP</title>
</head>
<body>
<form action="" name="img_compress" id="img_compress" method="post" enctype="multipart/form-data">
Upload: <input type="file" name="file" id="file"/>
<input type="submit" name="submit" id="submit" class="submit btn-success"/>
</form>
</body>
</html>