-1

I discovered this post to help me in resizing PNG/JPG & GIF images : Resize images with PHP, support PNG, JPG but I really don't understand how to use it in my own code "context", my context is lookin' like this:

  $filepath = $_FILES['file']['tmp_name'];

$fileSize = filesize($filepath);
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($fileinfo, $filepath);

if ($fileSize === 0) {
    die("Fail");
}

if ($fileSize > 3145728) { 
    die("The file is too large");
}

$allowedTypes = [
   'image/jpeg' => 'jpg',
   'image/png' => 'png',
   'image/gif' => 'gif'
];

if (!in_array($filetype, array_keys($allowedTypes))) {
    die("File is not allowed");
}
$filename = "imagenumber" . numbergenerate(); //numbergenerate() is a simple function which generates  5 random numbers to give a new label to the image


$extension = $allowedTypes[$filetype];
$targetDirectory = __DIR__ . "/uploads"; 

$newFilepath = $targetDirectory . "/" . $filename . "." . $extension;

 function resize($newWidth, $targetFile, $originalFile) {

        $info = getimagesize($originalFile);
        $mime = $info['mime'];
    
        switch ($mime) {
                case 'image/jpeg':
                        $image_create_func = 'imagecreatefromjpeg';
                        $image_save_func = 'imagejpeg';
                        $new_image_ext = 'jpg';
                        break;
    
                case 'image/png':
                        $image_create_func = 'imagecreatefrompng';
                        $image_save_func = 'imagepng';
                        $new_image_ext = 'png';
                        break;
    
                case 'image/gif':
                        $image_create_func = 'imagecreatefromgif';
                        $image_save_func = 'imagegif';
                        $new_image_ext = 'gif';
                        break;
    
                default: 
                        throw new Exception('Unknown image type.');
        }
    
        $img = $image_create_func($originalFile);
        list($width, $height) = getimagesize($originalFile);
    
        $newHeight = ($height / $width) * $newWidth;
        $tmp = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
        if (file_exists($targetFile)) {
                unlink($targetFile);
        }
        $image_save_func($tmp, "$targetFile.$new_image_ext");
    }

    resize(100,$newFilepath,$filepath);


  
//I removed the part below...
   $res = copy($filepath, $newFilepath); 

        if(!$res) {
            die("Can't move file. 1");
        
           }

           unlink($filepath);  

  

If anyone can help me understand how to use that function provided in the link above I would really appreciate it.

Main USSE
  • 3
  • 3
  • The linked question is an class, and the answer given replaces the resize method. If you copy the entire thing into your code, you should be able to use the resize method. Have you worked with classses in PHP before, you just need to start the class, and using the resize method: resize($newWidth, $targetFile, $originalFile). $originalFile and $targetFile requires the path to the existing file and where the new file should be stored. – Aprilsnar Oct 22 '22 at 19:40
  • But what exactly in my code should be the $targetFile and $originalFile??? – Main USSE Oct 23 '22 at 11:31
  • You could use your $filepath as the "originalFile", as this is the temporary file - and then the targetFile could be the $newFilepath (but you already have in your code). Then you can remove copy part of your code, and replace that with the resize function. Update your code, with this then we can from there figure out if there are more issues. – Aprilsnar Oct 23 '22 at 16:11
  • Thanks for your response, I tried what you wrote and it is not working at all , removing the copy function is triggering a blank page... – Main USSE Oct 23 '22 at 17:32
  • Can you please update you post, with current code, then I can maybe rewrite it to help. – Aprilsnar Oct 23 '22 at 17:58
  • I updated it ...btw I managed to fixed the blank page , it does work now , but after clicking upload button it simply redirects me back to my main page , I tried to simply put the resize function and then leave the copy function , but in that case the image is getting uploaded but no changes are made to it , it remains as uploaded.. – Main USSE Oct 23 '22 at 18:33
  • Not sure about you code, since it sounds like you might have more on that same page and not activated error_reporting. But take a look at my answer. – Aprilsnar Oct 24 '22 at 06:14

1 Answers1

0

Not fully sure why your code don't work, but I created this from your code and added some comments to explain for future visitors what the code does.

This works for me, give it a try. This does not redirect nor anything - please try to give it a call directly from a form like this - expected result is a blank page for this scenarie, but you can then find the upload folder and see the result:

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="file" id="file">
    <input type="submit" value="Upload Image" name="submit">
  </form>

upload.php:

<?php
/*
What is the objective: To upload an image, then resize it
This code is triggered from a form post.
*/

// Get temporary file (from upload form).
$tmpfile = $_FILES['file']['tmp_name'];

// Get information about file.
$fileSize = filesize($tmpfile);
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($fileinfo, $tmpfile);

// Incorrect filesize, expected to be higher than none.
if ($fileSize === false || $fileSize === 0) {
    die("Failed to upload image (filesize incorrect)");
}

// File cannot be larger than 3 megabytes.
if ($fileSize > 3145728) { 
    die("File cannot be larger than 3 megabytes");
}

// List of allowed filetypes.
$allowedTypes = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif'
];

// Filetype is not whitelisted.
if (!in_array($filetype, array_keys($allowedTypes))) {
    die("File is not allowed");
}

// Set filename, with a unique string, of the file we want to store.
$filename = "imagenumber" . uniqid(true); // https://www.php.net/manual/en/function.uniqid

// Set the directory we want to store
$targetDirectory = __DIR__ . "/uploads";

// Where we want the new file to be stored and named (without filetype).
$newFilepath = $targetDirectory . "/" . $filename;

// Resize image and store it (function from stack overflow).
resize(100, $newFilepath, $tmpfile);

// Delete temporary file.
unlink($tmpfile); 

// Following code could be stored in a differend file, and included in begining of this file.
// Code is from Resize images with PHP, support PNG, JPG (https://stackoverflow.com/questions/13596794/resize-images-with-php-support-png-jpg)
function resize($newWidth, $targetFile, $originalFile) {

    $info = getimagesize($originalFile);
    $mime = $info['mime'];

    switch ($mime) {
        case 'image/jpeg':
            $image_create_func = 'imagecreatefromjpeg';
            $image_save_func = 'imagejpeg';
            $new_image_ext = 'jpg';
            break;

        case 'image/png':
            $image_create_func = 'imagecreatefrompng';
            $image_save_func = 'imagepng';
            $new_image_ext = 'png';
            break;

        case 'image/gif':
            $image_create_func = 'imagecreatefromgif';
            $image_save_func = 'imagegif';
            $new_image_ext = 'gif';
            break;

        default: 
            throw new Exception('Unknown image type.');
    }

    $img = $image_create_func($originalFile);
    list($width, $height) = getimagesize($originalFile);

    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    if (file_exists($targetFile)) {
        unlink($targetFile);
    }

    $image_save_func($tmp, "$targetFile.$new_image_ext");
}

Please make sure to have created the upload folder at the same directory as this file is placed.

Aprilsnar
  • 521
  • 1
  • 5
  • 14
  • Thanks for your work , I checked what your code and I made few edits on my own based on yours, at the end there were some problems within my file , not in this code specifically , so my method and yours were both working but in different contexts , anyways , big thanks and good luck with your work , I see you really put effort into explaining this ! – Main USSE Oct 24 '22 at 17:03
  • You made a small mistake in your code, put always the function above the invoking , in VSCode it is verified as working but in PHP it will trigger an error . – Main USSE Oct 24 '22 at 17:06
  • Correct, as also mentioned in the comment above it, that it should properly be included/required in the beginning from a separate file as well. – Aprilsnar Oct 25 '22 at 11:06