我希望将图像上传到具有缩小图像大小的Mysql数据库。我可以成功上传图片,但不能缩小尺寸。如何上传和缩小图像。
例如,上传大小约为2MB的图像,我想压缩它(可能小于1MB)并将其上传到Mysql数据库。
这是我的代码:
if (isset($_POST['btn-save'])) {
if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$filename = $_FILES['userImage']['tmp_name'];
$filePath = $_FILES['userImage']['tmp_name'];
$image1 = imagecreatefrompng($filePath);
$image2 = imagecreatefromgif($filePath);
$exif = exif_read_data($_FILES['userImage']['tmp_name']);
if (!empty($exif['Orientation'])) {
$imageResource = imagecreatefromjpeg($filePath);
switch ($exif['Orientation']) {
case 3:
$image = imagerotate($imageResource, 180, 0);
break;
case 6:
$image = imagerotate($imageResource, -90, 0);
break;
case 8:
$image = imagerotate($imageResource, 90, 0);
break;
default:
$image = $imageResource;
}
}
imagejpeg($image, $filename, 20);
imagedestroy($imageResource);
imagedestroy($image);
imagejpeg($image1, $filename, 50);
imagedestroy($image1);
imagejpeg($image2, $filename, 50);
imagedestroy($image2);
$imgData = addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimagesize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO Database (imageType, imageData) VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysqli_query($conn, $sql) or die("<b>Error!</b> <br/>" . mysqli_error());
if (isset($current_id)) {
echo "post";
} else {
echo "fail";
}
}
} // post btn-save