1

Could you help me with this issue? I need to resize image on upload using some simple script.

CODE:

<form method="post" enctype="multipart/form-data">
    <input type="file" name="obrazky[]" />
    <input type="submit" value="Nahrát na server!" />
</form>

<?php


// konfigurace
$uploadDir = 'imgs/nahrane'; // dir
$allowedExt = array('jpg', 'jpeg', 'png', 'gif'); // ok formats
if(isset($_FILES['obrazky']) && is_array($_FILES['obrazky']['name'])) {
    $counter = 0;
    $allowedExt = array_flip($allowedExt);
    foreach($_FILES['obrazky']['name'] as $klic => $nazev) { // make variable $nazev
        $nazev = htmlspecialchars($nazev, ENT_QUOTES);
        $fileName = basename(time() . ".png");
        $fileName = sprintf(time() . ".png", pathinfo($nazev, PATHINFO_EXTENSION));
        $tmpName = $_FILES['obrazky']['tmp_name'][$klic];
        $fileName = htmlspecialchars($fileName, ENT_QUOTES);
        // check
        if(
            !is_uploaded_file($tmpName)
            || !isset($allowedExt[strtolower(pathinfo($fileName, PATHINFO_EXTENSION))])
        ) {
            // bad format
            continue;
        }
        // move
        if(move_uploaded_file($tmpName, "{$uploadDir}".DIRECTORY_SEPARATOR."{$fileName}")) {
            ++$counter;
        }
  }
    if ($counter > 0)
    echo "<hr><p>Uploaded {$counter} z ".sizeof($_FILES['obrazky']['name'])." thank you!<br>
    <br>
    <b>LINKS</b>:<br>
    href:<br> 
    <a href='$uploadDir/$fileName'  target='_blank'>$uploadDir/$fileName</a><br>
 
    else
    echo "<hr><b><font color='red'>ERROR: Bad format or no image uploaded.</font></b><br>"; 
}
 
?>

I did allready search on google and stackoverflow and i tried allready something, but i dont get it work.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
Radek Homola
  • 390
  • 1
  • 3
  • 11
  • use this class its simple and much powerful [link](https://www.verot.net/php_class_upload.htm) – Samir Nabil Oct 29 '16 at 10:56
  • look at this: [http://stackoverflow.com/questions/18805497/php-resize-image-on-upload](http://stackoverflow.com/questions/18805497/php-resize-image-on-upload) – Mathies Gielen Oct 29 '16 at 11:35

1 Answers1

1

This has always worked rather well for me:

$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle );

$image->scaleImage(100,200,FALSE);

$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);

You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight(); and $image->getImageWidth();.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133