I have function that gets uploaded file, save it, then crop it with imagecrop and now I need to save it again to the media. I know the way, how to do that with vanilla PHP, but I need file to be inserted (meta data) to the database, not only save the file to the server.

With this function, I am inserting the file to the media:

$attachmentId = media_handle_upload('image', 0);

Then I am getting file path:

$img= get_attached_file($attachmentId);

Then I am using a custom for cropping the image:

function crop($filePath, $cropWidth, $cropHeight, $cropX, $cropY){

    // returns imageCreateFromJpeg($filepath), 
    $image = $this->createImageFromAnyType($filepath); 

    $cropped = imagecrop($image, ['x' => $cropX, 
                       'y' => $cropY, 'width' => $cropWidth, 'height' => $cropHeight]);

    return $cropped ? imagejpeg($cropped) : false;

Now I have this resource imagejpeg($cropped) which I don't know how to save, similar as media_handle_upload.

  • Shouldn't you be cropping it before uploading? media_handle_upload() creates the attachment and inserts the information into the database. Your code is modifying an image that's already been uploaded to the media library. Commented Jan 24, 2019 at 8:52
  • No cropping before upload, but I think the logic will be same. I need to upload it with media_handle_upload, then crop it and save it again as another image. At the end , there are two images.
    – gdfgdfg
    Commented Jan 24, 2019 at 14:53

1 Answer 1


What I did was to get media folder and save there the cropped image. After that update meta data:

$imageToCropPath= get_attached_file($attachmentId); // Get file path to the image that will be cropped
$img = imageCreateFromJpeg($imageToCropPath);

$croppedImage = imagecrop($img, ['x' => $cropX, 
                                 'y' => $cropY, 
                                 'width' => $cropWidth, 
                                 'height' => $cropHeight]);

$uniqueId = md5(uniqid()); // Create unique name for the new image

$imagePath = wp_upload_dir()['path'] . '/' . $uniqueId . '.jpg';
imagejpeg($croppedImage,  $imagePath); // Save image in the media folder

$attachment = array(
    'post_mime_type' => 'image/jpeg',
    'post_title' => basename($imagePath),
    'post_content' => '',
    'post_status' => 'inherit'

$croppedAttachmentId = wp_insert_attachment( $attachment, $imagePath );

$attachedData = wp_generate_attachment_metadata( $croppedAttachmentId, $imagePath);

wp_update_attachment_metadata( $croppedAttachmentId , $attachedData );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.