1

i need help for this, i spend all my day for try to resize a picture in PHP :(((.

I find a good subject Resize the image-file before uploading; Could we overwrite the temp file & upload?

BUT, when i try to use for me my add.php return me a little white square like this : enter image description here

and my image is not resized in my folder.

I propably forget to change something in the code or failed to use but, i really need help Thanks you.

require_once('../connexion.php');

extract($_POST);

// This will count total images selected.
$TotalImage = count($_FILES['image']['name']);
$domaine   = isset($_POST['domaine']) ? $_POST['domaine'] : null;

for($i = 0;$i<$TotalImage;$i++)
{ 
    $tempFile = $_FILES['image']['tmp_name'][$i];
    $image_name = $_FILES['image']['name'][$i];
    $ext = strtolower(substr(strrchr($image_name, '.'), 1));
    $target_path = $_SERVER['DOCUMENT_ROOT'].'/AprimeWeb/img/sliders/'.$domaine .'/'.$image_name;

    $image_properties = getimagesize($tempFile);
    $image_width = $image_properties[0];
    $image_height = $image_properties[1];
    $percent = 0.5; //Percentage by which the image is going to be resized

    $newWidth = $image_width * $percent;
    $newHeight = $image_height * $percent;

    if ($ext == "jpeg" || $ext == "jpg") {
        header('Content-type: image/jpeg');
        $thumb = imagecreatefromjpeg($tempFile);
    } elseif ($ext == "png") {
        header('Content-type: image/png');
        $thumb = imagecreatefrompng($tempFile);
    }

    $modifiedFile = imagecreatetruecolor($new_width, $new_height);

    imagecopyresampled(
        $modifiedFile,
        $thumb, 
        0, 
        0,
        0, 
        0,
        $new_width, 
        $new_height, 
        $width,
        $height
    );

      if(imagejpeg($tempFile, $target_path))
      {
         $sql = "INSERT INTO images SET name = '$image_name', domaine = '$domaine'" ;
            $return['success'] = $connexion->exec($sql);
            echo json_encode($return);
      }
      header('Location: ../admin_sliders.php');
}

EDIT ANSWER---------------------------------------------------------------

The good way was provide by @keziah but he do a little bit mistake, for make the code work you need to add a for condition with a count($_FILES['image']['name']); and a [$i] at the end of each $_FILES['image']['*****']

Like this

    <?php
// Image config

require_once('../connexion.php');

$max_image_size = 500;            //Maximum image size (height and width) (pixels)
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/AprimeWeb/img/sliders/'.$_POST['domaine'] .'/'; //upload directory ends with /
$jpeg_quality = 90;               // jpeg quality (percent)
$domaine   = isset($_POST['domaine']) ? $_POST['domaine'] : null;
$TotalImage = count($_FILES['image']['name']); //give the number of image you upload
extract($_POST);


for($i = 0;$i<$TotalImage;$i++){
if (isset($_FILES['image']['name'][$i])) {
    // check $_FILES['image'] not empty
    if (!isset($_FILES['image']['name'][$i]) || !is_uploaded_file($_FILES['image']['tmp_name'][$i])) {
        die('Image file is Missing!');

    }

    // uploaded file info
    $image_name = $_FILES['image']['name'][$i];     //file name
    $image_size = $_FILES['image']['size'][$i];     //file size
    $image_temp = $_FILES['image']['tmp_name'][$i]; //file temp
    $image_size_info = getimagesize($image_temp); //get image size

    if ($image_size_info) {
        $image_width = $image_size_info[0];     //image width
        $image_height = $image_size_info[1];    //image height
        $image_type = $image_size_info['mime']; //image type
    } else {
        die("Make sure image file is valid!");
    }

    // creates new image from given file 
    // also, it validates the accepted image format
    switch ($image_type) {
        case 'image/png':
            $image_res = imagecreatefrompng($image_temp);
            break;
        case 'image/gif':
            $image_res = imagecreatefromgif($image_temp);
            break;
        case 'image/jpeg': case 'image/pjpeg':
            $image_res = imagecreatefromjpeg($image_temp);
            break;
        default:
            $image_res = false;
    }

    if ($image_res) {
      var_dump($image_res);
        //Get file extension and name to construct new file name 
        $image_info = pathinfo($image_name);
        $image_extension = strtolower($image_info["extension"]); //image extension
        $image_name_only = strtolower($image_info["filename"]); //file name only, no extension
        //create a random name for new image (Eg: fileName_293749.jpg) ;
        $new_file_name = $image_name_only . '_' . rand(0, 99999) . '.' . $image_extension;

        //folder path to save resized images and thumbnails
        $image_save_folder = $destination_folder . $new_file_name;

        // proportionally resize image
        if (normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality)) {

            /* Now, output image to user's browser or store information in the database */

            $sql = "INSERT INTO images SET name = '$new_file_name', domaine = '$domaine'" ;
            $return['success'] = $connexion->exec($sql);
            echo json_encode($return);
        }

        imagedestroy($image_res); //freeup memory
    }
    else {
        die('Invalid image format.');
    }
}
}

1 Answer 1

1

The normal_resize_image()

Params

  • Source - imagecreatefrom*($_FILES['image']['tmp_name']); - * means any image format
  • Destination - uploads/ - your uploads directory
  • Image type - getimagesize($_FILES['image']['tmp_name'])['mime'] - image mime type
  • Max size - your custom image size would be 200, 400, 500 pixels
  • Image width - getimagesize($_FILES['image']['tmp_name'])[0] - image width
  • Image height - getimagesize($_FILES['image']['tmp_name'])[1] - image height
  • Quality - The JPEG quality would be 80, 90, 100 percent

Image resizer

<?php
function normal_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality) {

    if ($image_width <= 0 || $image_height <= 0) {
        return false;
    } //return false if nothing to resize
    //do not resize if image is smaller than max size
    if ($image_width <= $max_size && $image_height <= $max_size) {
        if (save_image($source, $destination, $image_type, $quality)) {
            return true;
        }
    }

    //Construct a proportional size of new image
    $image_scale = min($max_size / $image_width, $max_size / $image_height);
    $new_width = ceil($image_scale * $image_width);
    $new_height = ceil($image_scale * $image_height);

    $new_canvas = imagecreatetruecolor($new_width, $new_height); //Create a new true color image
    //Copy and resize part of an image with resampling
    if (imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)) {
        save_image($new_canvas, $destination, $image_type, $quality); //save resized image
    }

    return true;
}
?>

The save_image()

Params

  • Source - your image source (same as above)
  • Destination - uploads folder/directory (same as above)
  • Image type - image mime type (same as above)
  • Quality - JPEG quality (same as above)

Saves image to resource file

<?php
function save_image($source, $destination, $image_type, $quality) {
    switch (strtolower($image_type)) {//determine mime type
        case 'image/png':
            imagepng($source, $destination);
            return true; //save png file
            break;
        case 'image/jpeg':
        case 'image/pjpeg':
            imagejpeg($source, $destination, $quality);
            return true; //save jpeg file
            break;
        default: return false;
    }
}

Sample Usage

<?php
// Image config
$max_image_size = 500;            //Maximum image size (height and width) (pixels)
$destination_folder = 'uploads/'; //upload directory ends with /
$jpeg_quality = 90;               // jpeg quality (percent)

if (isset($_FILES['image'])) {

    // check $_FILES['image'] not empty
    if (!isset($_FILES['image']) || !is_uploaded_file($_FILES['image']['tmp_name'])) {
        die('Image file is Missing!');
    }

    // uploaded file info
    $image_name = $_FILES['image']['name'];     //file name
    $image_size = $_FILES['image']['size'];     //file size
    $image_temp = $_FILES['image']['tmp_name']; //file temp

    $image_size_info = getimagesize($image_temp); //get image size

    if ($image_size_info) {
        $image_width = $image_size_info[0];     //image width
        $image_height = $image_size_info[1];    //image height
        $image_type = $image_size_info['mime']; //image type
    } else {
        die("Make sure image file is valid!");
    }

    // creates new image from given file 
    // also, it validates the accepted image format
    switch ($image_type) {
        case 'image/png':
            $image_res = imagecreatefrompng($image_temp);
            break;
        case 'image/gif':
            $image_res = imagecreatefromgif($image_temp);
            break;
        case 'image/jpeg': case 'image/pjpeg':
            $image_res = imagecreatefromjpeg($image_temp);
            break;
        default:
            $image_res = false;
    }

    if ($image_res) {
        //Get file extension and name to construct new file name 
        $image_info = pathinfo($image_name);
        $image_extension = strtolower($image_info["extension"]); //image extension
        $image_name_only = strtolower($image_info["filename"]); //file name only, no extension
        //create a random name for new image (Eg: fileName_293749.jpg) ;
        $new_file_name = $image_name_only . '_' . rand(0, 99999) . '.' . $image_extension;

        //folder path to save resized images and thumbnails
        $image_save_folder = $destination_folder . $new_file_name;

        // proportionally resize image
        if (normal_resize_image($image_res, $image_save_folder, $image_type, $max_image_size, $image_width, $image_height, $jpeg_quality)) {

            /* Now, output image to user's browser or store information in the database */
            echo '<div align="center">';
            echo '<img src="uploads/' . $new_file_name . '" alt="Resized Image">';
            echo '</div>';

            // COde to store the image into database
        }

        imagedestroy($image_res); //freeup memory
    }
    else {
        die('Invalid image format.');
    }
}
1
  • Thanks you, but can you tell me how to use that ?
    – AlexDemzz
    May 30, 2016 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.