5

I am generating dynamic images to a directory in craft/storage. I need to be able to use these generated images on the front-end inside templates. Is there a helper method for this, or some way to use these images in my templates?

4

Since craft/storage/ is not publicly accessible, your only real option here is to serve them through Craft as Resource Requests. (This is the vehicle through which Craft serves up all of the CP’s front end resources, which live in craft/app/resources/.)

The actual resource URLs will depend on the site’s resourceTrigger config setting, so to generate the URLs you should use URLHelper::getResourceUrl():

$url = UrlHelper::getResourceUrl('myplugin/some/path.jpg');

Your templates can call the corresponding resourceUrl() function as well:

{{ resourceUrl('myplugin/some/path') }}

Then you will need to add a getResourcePath hook method to your primary plugin class, which would detect incoming resource requests and resolve them to the actual server path in craft/storage/.

public function getResourcePath($path)
{
    // Does this path start with "myplugin/"?
    if (strncmp($path, 'myplugin/', 9) == 0)
    {
        // Return the path to the file in craft/storage/
        return craft()->path->getStoragePath().'myplugin/'.substr($path, 9);
    }
}

It’s worth mentioning that you’re always going to get worse performance out of serving files through PHP than you would if they were located somewhere that’s publicly accessible. So you might just want to have the user create a new folder somewhere under their web root, and have them specify the path/URL to that folder, just like local asset sources.

2
  • Is there a way to find the 'public' folder? I can't find anything in PathService or constants. Nov 11 '16 at 22:44
  • @ElliotLewis Sorry just saw your comment. Can you please post that as a new question? Feb 27 '17 at 19:12

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.