3

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();
     }
}

1 Answers1

1

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();  
Rafa Jaques
  • 107
  • 7
  • after that i can save $imageData variable as before? (thanks for your answer) – Giuseppe De Paola Dec 15 '15 at 11:29
  • 1
    First you load the image. Then you create a new image to put the resized sample. Then you resize it. At the end, you output it to the browser, but you don't want that. So, you start the output buffer and catches the data for storing. – Rafa Jaques Dec 15 '15 at 11:31
  • but imagejpeg($tmp_image) function what gonna do? – Giuseppe De Paola Dec 15 '15 at 11:34
  • imagejpeg() outputs the image to the browser. Since you're not going to show it to the user, we just capture the image content using the output buffer. – Rafa Jaques Dec 15 '15 at 11:35
  • okok, i'll try it..i already accept the answer beacuse i've used it in another page but i wasn't sure if i can use this also if the image was uploaded by browser in the moment of resizing..i used to use the code when i get the data by db – Giuseppe De Paola Dec 15 '15 at 11:38
  • It should probably work. But first you need to know the mime-type of the file. Then change imagejpeg to another function when needed. – Rafa Jaques Dec 15 '15 at 11:39
  • yes it work..but i don't know how to mark a comment as the correct answer – Giuseppe De Paola Dec 21 '15 at 14:20