简体   繁体   中英

Javascript Function And PHP Code On Resizing Image On Upload

I have a javascript way of uploading an image. Now I have my codes below showing the function upload image, I need this function to resize or allow to me to set image size to be save into database.

function upload_image()
{
    if(isset($_FILES["image1"])) 
    {
        $extension = explode('.', $_FILES['image1']['name']);
        $new_name = rand() . '.' . $extension[1];
        $destination = 'machine_images/' . $new_name;
        move_uploaded_file($_FILES['image1']['tmp_name'], $destination);
        return $new_name;
    }
}

To resize image, you can use php imagecopyresized function.

imagecopyresized — Copy and resize part of an image.

Ex:

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb);
?>

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM