Jump to content

Alternative method for storing image variations


ZGD
 Share

Recommended Posts

Not sure if this has been discussed before, but is it possible to use a different method for storing image variations with PW? For example, would it be possible that instead of storing variations like this:

/image.jpg
/image.2000x0.jpg
/image.0x900.jpg


Variations were instead stored like this:

/image.jpg
/2000x0/image.jpg
/0x900/image.jpg


Normally the default method is fine, but we are working on a project where the image filenames may need to remain unchanged, but variations still produced.

If anyone has any information about this it would be much appreciated!

EDIT: Having looked at the size method in the Pageimage class, it looks like this isn't something that could be changed easily.

 

Link to comment
Share on other sites

4 hours ago, Robin S said:

The built-in image sizing methods are convenient but they're not the only way to resize an image. You could use a third-party PHP library such as WideImage and save your images with any naming or directory structure you need.

module alert!

  • Like 1
Link to comment
Share on other sites

Turns out it's not difficult to do this using the core ImageSizer. Here's a function showing the basics - could be turned into a module, enhanced with some error checking, etc.

/**
 * Resize Pageimage using custom name/path
 *
 * @param Pageimage $pageimage
 * @param int $width
 * @param int $height
 * @param array $options
 *
 * @return string
 * 
 */
function resizeImage($pageimage, $width = 0, $height = 0, $options = array()) {
    $filename = $pageimage->filename();
    $basename = $pageimage->basename();
    $path = rtrim($filename, $basename);
    $dirname = $width . 'x' . $height;
    $variation_name = $path . $dirname . '/' . $basename;
    $variation_url = rtrim($pageimage->url(), $basename) . $dirname . '/' . $basename;

    $force_new = isset($options['forceNew']) ? $options['forceNew'] : false;
    if(!file_exists($variation_name) || $force_new) {
        wire('files')->mkdir($path . $dirname . '/');
        copy($filename, $variation_name);
        $sizer = new ImageSizer($variation_name);
        $sizer->setOptions($options);
        $sizer->resize($width, $height);
        wire('files')->chmod($variation_name);
    }

    return $variation_url;
}

// example
$image = $page->images->first();
$src = resizeImage($image, 500, 300);
echo "<img src='$src'>";

 

 

  • Like 4
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...