Jump to content

Using the API : How can I grab an image from a field, resize it, then upload the resized image to a new field?


John W.
 Share

Recommended Posts

Hi,

I'm having trouble figuring how how to do this. Basically, I have a large number of businesses that already have images. What I'm trying to do is grab the first image, resize it to make a copy, then add the copy to another image field.

 

<?php

// get the first image from an array of images
// create a new preview image
// save the new preview image to another field along with the description

$businesses = $pages->find("template=business");
foreach($businesses as $b) {

     $imagetouse = $b->page_slides->first();

     $newpreviewimage = $imagetouse->size(1200,630);

  // this is confusing me , see next comments
  
     $b->images->add($newpreviewimage);
     
  // it seems in the above line that it would be logical to add something like this instead:
  // $b->seo_preview_image->url = $b->images->add($newpreviewimage);

     $b->seo_preview_image->description = $imagetouse->description;

     $b->save();

}

?>

 

Link to comment
Share on other sites

1 hour ago, John W. said:
 $b->save();

Above should throw an error that you need to set output formatting of before attempting to modify the page. I am guessing you are testing with debug off. Try below. It should work.

<?php

namespace ProcessWire;
$b->of(false);
$b->images->add($newpreviewimage);
$b->save();

 

  • Like 1
Link to comment
Share on other sites

44 minutes ago, kongondo said:

Above should throw an error that you need to set output formatting of before attempting to modify the page. I am guessing you are testing with debug off. Try below. It should work.

<?php

namespace ProcessWire;
$b->of(false);
$b->images->add($newpreviewimage);
$b->save();

 

Absolutely wonderful!  Thank you so much.

(Just a note for anyone reading this, the add() will include the photo along with the description and any image tags.)

I'll leave the working code below.

<?php
// get the first image from an array of images
// create a new preview image
// save the new preview image to another field along with the description and keyword tags

namespace ProcessWire;

$businesses = $pages->find("template=business");
foreach($businesses as $b) {
    $b->of(false);
     $imagetouse = $b->page_slides->first();

     $newpreviewimage = $imagetouse->size(1200,630);

     $b->seo_preview_image->add($newpreviewimage);
     $b->save();

}

?>

 

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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...