jquery 如果图像太大,请调整图像大小,将其发送到数据库和图像文件夹

nuypyhwy  于 2022-12-29  发布在  jQuery
关注(0)|答案(1)|浏览(90)

我在调整图片大小并将其上传到数据库和图片文件夹时遇到了问题。我尝试了一些方法,但仍然无法解决这个问题。以下是我的代码:

// AJAX in the <head> HTML tag
$(function(){
$('#add_recipes_form').on('click', '#add', function(e){
    e.preventDefault();

    let sendForm = true;

    let fileInput = document.querySelector('#upload_image');
    let image = new Image();
    image.src = URL.createObjectURL(fileInput.files[0]);
   
        // sendForm = form validation

    if (sendForm){
        image.onload = function() {
        let width = image.naturalWidth;
        let height = image.naturalHeight;
        if (width > 1920 || height > 1080) {
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d');
            canvas.width = 1920;
            canvas.height = 1080;
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
            canvas.toBlob(function(resizedImageBlob) {
                let form = document.querySelector('#add_recipes_form');
                let formData = new FormData(form);
                formData.set('image', resizedImageBlob, 'resized-image.jpg');
                $.ajax({
                    type: "post",
                    url: 'Php/add-recipes.php',
                    data: new FormData(form),
                    processData: false,
                    contentType: false,
                    success: function(){
                        $("#add").addClass('sent');
                    },
                    error: function(){
                        $("#add").addClass('error');
                    }
                });
            }, 'image/jpeg');
        }
        }
    }
});
});
// shortened HTML form
<form method="POST" action="Php/add-recipes.php" enctype="multipart/form-data" id="add_recipes_form" class="add-form">
  <div class="input-div s1-image">
    <label for="image">Image (jpg, png)*</label>
    <label for="upload_image" id="file_style">Choose image</label>
    <input type="file" style="display:none;" id="upload_image" name="image" accept="image/*" onchange="loadFile(event)" class="required2">
  </div>

  <div class="form-s1-right">
    <img id="output" src="Images/placeholder-image.svg" alt="Uploaded Image">
    <script>
    var loadFile = function(event) {
        var output = document.getElementById('output');
        output.src = URL.createObjectURL(event.target.files[0]);
        output.onload = function() {
        URL.revokeObjectURL(output.src);
        }
    };
    </script>
  </div>
</form>
// shortened PHP script
$con = mysqli_connect("localhost", "root", "", "cookbook");
                    
    $name = $_POST["name"];
    $image = $_FILES['image']['name'];

    $sql = "
      INSERT INTO
      recipes(`name`, `image`) 
      VALUES('$name', '$image');
    ";
                
    $target = "../Recipe_img/".basename($image);

    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
    }

    $var = mysqli_multi_query($con,$sql);

mysqli_close($con);

注:还有更多的代码,我想只显示重要的部分。我不知道如何上传一个图像,调整大小,如果必要的话(如果大于1920 x 1080 px)并将其发送到Recipe_img文件夹(../Recipe_img)和数据库,这样我就可以获得图像名称以便以后使用。(用JS画布尝试了几次失败),但是没有任何东西调整上传到文件夹的图像的大小。有没有办法做到这一点?

1l5u6lss

1l5u6lss1#

我认为你可以在php中使用GD来调整图片大小

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

$target = "../Recipe_img/".basename($image);
$img = resize_image($target, 1920, 1080);

相关问题