Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize image on upload

Tags:

php

image

resize

I'm wondering what i'm gonna do. If i want to resize an image when i insert it into the db.. I know that it's better to don't save image on database.. But i have to do this for save space on my little server.. Currently i use this code to save the image:

if (isset($_FILES['immagine']) && $_FILES['immagine']['size'] > 0)
{
  $imageName = $_FILES["immagine"]["name"];
  $imageData = file_get_contents($_FILES["immagine"]["tmp_name"]);
  $imageType = $_FILES["immagine"]["type"];
  if(substr($imageType,0,5)=="image")
     {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

         $stmt = $dbh->prepare("UPDATE `".$_SESSION['id']."`  SET immagine = ?, type = ?, profilo = 1 WHERE profilo = 1");
         $stmt->bindParam(1,$imageData,PDO::PARAM_LOB);
         $stmt->bindParam(2,$imageType,PDO::PARAM_STR);
         $stmt->execute();
     }
}
like image 958
Giuseppe De Paola Avatar asked Feb 27 '26 07:02

Giuseppe De Paola


1 Answers

You should try using GD.

// Loads the image
$img = imagecreatefromjpeg($_FILES["immagine"]["tmp_name"]); // Assuming it's a jpeg

// Creates a image to put the thumbnail
$tmp_img = imagecreatetruecolor(<thumbnail width>, <thumbnail height>)

// Resizes the image
imagecopyresampled ( $tmp_img, $img, 0, 0, 0, 0, <thumbnail width>, <thumbnail height>, <original width>, <original height>); // The zeroes are the offsets

// Starts output buffer to not let the image reach the browser
ob_start();

// Render the image
imagejpeg($tmp_image); 

// Capture the image data
$imageData = ob_get_clean();  
like image 125
Rafa Jaques Avatar answered Feb 28 '26 19:02

Rafa Jaques



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!