How to Image Resize using PHP Before Uploading

The uploaded image can be of any size of course, but you want all the profile images to fit inside a certain frame. You could just set the dimensions on the image tag to this size. PHP make this very simple you can do any kind of image manipulation you want with the help of its GD Library. In this tutorial we will show you an easy and quick way to PHP image resize before uploading it to the server. You may also like How to Resize and Crop Image using PHP and jQuery.

HTML and PHP Code

<?php
    define('DB_SERVER', "localhost");
    define('DB_USER', "root");
    define('DB_PASS', "");
    define('DB_DATABASE', "whatsappdwld_db");
    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
    if(isset($_POST['upload_image']))
    {
        $upload_image = $_FILES[" image1 "][ "name" ];
        $folder = "images/";
        move_uploaded_file($_FILES[" image1 "][" tmp_name "], $folder.$_FILES[" image1 "][" name "]);
        $file = '/xampp/htdocs/images/'.$_FILES[" image1 "][" name "];
        $uploadimage = $folder.$_FILES[" image1 "][" name "];
        
        $newname = $_FILES[" image1 "][" name "];
        
        $resize_image = $folder.$newname."_resize.jpg"; 
        $actual_image = $folder.$newname.".jpg";
        list( $width,$height ) = getimagesize( $uploadimage );
        $newwidth = 350;
        $newheight = 350;
        $thumb = imagecreatetruecolor( $newwidth, $newheight );
        $source = imagecreatefromjpeg( $resize_image );
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagejpeg( $thumb, $resize_image, 100 ); 
        $out_image=addslashes(file_get_contents($resize_image));

        $insertquery = " INSERT INTO resize_images (image)VALUES('".$out_image."') ";
        $result = mysqli_query($con,$insertquery);

    }   
?>

<html>
    <body>
        <form method="POST" action="getdata.php" enctype="multipart/form-data">
            <input type="file" name="image1">
            <input type="submit" name="upload_image" value="Upload">
        </form>
    </body>
</html>

For more details and PHP image manipulations functions you can learn from this site.

Leave a Reply

Your email address will not be published. Required fields are marked *