Home » Php » How to save cropped image to a directory with Jcrop using PHP

How to save cropped image to a directory with Jcrop using PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I can crop my images and click on crop. but then something goes wrong, because i don’t know exactly how to save this image.

I use imagecreatefromjpeg from php.
this code look like this:

<?php
SESSION_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = 200;
$targ_h = 400;
$jpeg_quality = 90;

$src = $_SESSION['target_path'];
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);

//header('Content-type: image/jpeg');
imagejpeg($dst_r, 'uploads/cropped/' . 'filename');

exit;
}

?>

My php code for saving the original image looks like this:

     <?php 
         session_start();
         $target = "uploads/"; 
         $target = $target . basename( $_FILES['filename']['name']) ; 
         $_SESSION['target_path'] = $target;

         $ok=1; 
         if(move_uploaded_file($_FILES['filename']['tmp_name'], $target)) 
         {
         echo "De afbeelding *". basename( $_FILES['filename']['name']). "* is geupload naar de map 'uploads'";
         } 
         else {
         echo "Sorry, er is een probleem met het uploaden van de afbeelding.";
         }
    ?> 

how do i save the cropped image?
and is there a way to save the cropped image by overwriting the original so i get only the cropped image?

thanks in advance.

EDIT:
I can save 1 photo now. i edited my code to:
imagejpeg($dst_r, ‘uploads/cropped/’ . $filename .’boek.jpg’);
But i have to make a function who can save multiple files with each another name. and maybe overwrite the original image, who is saved in ‘uploads/’

How to&Answers:

I am going to reply to what seems to be the question now:

But i have to make a function who can save multiple files with each
another name. and maybe overwrite the original image, who is saved in
‘uploads/’

An easy method to do this would be to add the timestamp in the filename, this way everytime the operation is executed, you get a new filename. Doing something along the lines of:

imagejpeg($dst_r, 'uploads/cropped/' . $filename . time() . 'boek.jpg');

Will save a new image everytime.

When you want to overwrite the original, simply assign the right path

imagejpeg($dst_r, 'uploads/' . $filename .'.jpg');

Edit: What seems to be the problem is getting the right file name, without hardcoding ‘boek.jpg’.

The original code posted used the string filename when saving the image

imagejpeg($dst_r, 'uploads/cropped/' . 'filename');

What you want to do, is deduce the filename from $src. To do so, simply use the function basename (documentation here), so you will have:

imagejpeg($dst_r, 'uploads/cropped/' . basename($src)); // basename will already contain the extension