1

Is there a way to copy an uploaded image in the assets.onSaveAsset event?

I want to make a copy of the original uploaded image (for internal purposes) and after that I want to add a copyright text on the uploaded image (for displaying on webpage).

UPDATE Some more info, to prevent missunderstandings: I use the BusinessLogicPlugin. Users can upload a picture which should be stored in S3. First I want to make a copy of this picture and after that to the picture should be added a small text. The copy works fine.

But now I want to modify the uploaded image.

My Code:

craft()->on('assets.onSaveAsset', function(Event $event) {

  static $recursionLevel = 0; // is set only once

  if ($recursionLevel == 0 ) {

    if ($event->params["isNewAsset"]) {
      $recursionLevel++;

      $asset = $event->params['asset'];
      $remoteFile = $asset->getUrl();

      // get remote image and store in temp path
      $imageInfo = pathinfo($remoteFile);
      $tempPath  = CRAFT_STORAGE_PATH . 'runtime/temp/' . $imageInfo['basename'];
      file_put_contents($tempPath, fopen($remoteFile, 'r'));

      // only JPEG allowed
      $im = @ImageCreateFromJPEG ($tempPath);
      $textcolor = imagecolorallocate($im, 0, 0, 255);
      // add text and save to original path
      imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);
      imagejpeg($im, $tempPath);

      // update the image, but how?!

    }
  }
});

How can I update the asset with the new generated file in $tempPath?

2

I'm thinking you should use the onBeforeUploadAsset event for this instead. You can get the path to the temporary location on disk via the path parameter like so:

$path = $event->params['path'];

From there, you can make a copy of the file and save to whatever location you want. You can also watermark the original and save it back to the same temporary location and let the request continue.

| improve this answer | |
  • I get "Undefined variable: params". I use the BusinessLogicPlugin to implement this. craft()->on('assets.onBeforeSaveAsset', function(Event $event) { } I tried $event->params["path"], too... Or do I have to use an other approach here? EDIT & INFO: The file is stored in S3. – Marco Jun 28 '17 at 12:14
  • Sorry, typo on my part. $event->params['path'] should work, though. What does it return for you? – Brad Bell Jun 28 '17 at 22:11
  • It still shows: Undefined index: path craft()->on('assets.onBeforeSaveAsset', function(Event $event) { echo $event->params['path']; }); – Marco Jun 29 '17 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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