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?

1 Answer 1

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.

3
  • 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
    Commented Jun 28, 2017 at 12:14
  • Sorry, typo on my part. $event->params['path'] should work, though. What does it return for you?
    – Brad Bell
    Commented Jun 28, 2017 at 22:11
  • It still shows: Undefined index: path craft()->on('assets.onBeforeSaveAsset', function(Event $event) { echo $event->params['path']; });
    – Marco
    Commented Jun 29, 2017 at 10:49

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.