Jump to content

Copy an image from one field to another on the same page


Marc
 Share

Recommended Posts

I want to use the API to duplicate an image from one field to another (on the same page). The duplicated image should be a new file so both fields should not point to the same physical file. The field that holds the image that I want to duplicate is called 'image_front' and the duplicated image should go to a field called 'image_thumb'. Any image that is already attached to image_thumb should be removed because it should hold only one file. The same goes for image_front, it should have only one image. Here's what I have so far:

$original = $page->image_front;
$file = $original->getFile($original);
$new = $original->clone($file);
$page->save();

$page->image_thumb = $new;
$page->save('image_thumb');

This works in the sense that the image is successfully cloned but it is attached to both fields so both fields end up have their original image plus the cloned image. 'Image_thumb' should only have the cloned image and 'image_front' should only have the original image. What would be the best way to remove those images and am I even approaching this correctly?

Link to comment
Share on other sites

  On 3/27/2018 at 11:05 AM, dragan said:

May I ask why you want to clone an image in the first place?

If you need thumbnails, just use 

$image->size($width, $height, $options)

in your templates.

Expand  

I understand I can generate different sizes and that is exactly what I'm doing right now. I do some checks to see if the uploaded thumbnail is of high enough quality by checking its dimensions and if it is not, I fallback to the image_front field which is always of higher quality and I resize on the fly to the correct dimensions. I want to get rid of these checks so I want to do a one time replacement of a bunch of thumbnails by cloning the image_front image to the thumbnail field.

Link to comment
Share on other sites

I figured it out, hopefully this might be useful to others as well:

// Remove current thumbnail first.
$currentThumb = $page->image_thumb->first();
$page->image_thumb->delete($currentThumb);
// Get the image we want to copy.
$original = $page->image_front;
$file = $original->getFile($original);
// Clone that image and append it to the image_thumb field.
$new = $original->clone($file, array('action' => 'append', 'pagefiles' => $page->image_thumb));
$page->save();

I noticed that this does not work if the filename of the file you are trying to clone ends with -0 (e.g. myfile-0.jpg). I think that is a bug which I'll post to GitHub.

  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...