Code Monkey home page Code Monkey logo

timmy's Introduction

Timmy

Timmy is an opt-in library/plugin to make it more convenient to work with responsive images. It was designed to be used with Timber, but should work with all your WordPress projects.

In your Twig template, you can do this:

<img{{ post.thumbnail|get_timber_image_responsive('custom-6') }}>

To get this:

<img srcset="https://www.example.org/wp-content/uploads/2016/02/header_example-480x206-c-default.jpg 480w,
    https://www.example.org/wp-content/uploads/2016/02/header_example-768x329-c-default.jpg 768w,
    https://www.example.org/wp-content/uploads/2016/02/header_example-1400x600-c-default.jpg 1400w,
    https://www.example.org/wp-content/uploads/2016/02/header_example-2800x1200-c-default.jpg 2800w"
src="data:image/gif;base64,R0lGODlhAQABAAAAADs="
sizes="100vw"
alt="Your alt text"
>

Documentation

Features

Timber already comes with a set of really nice features for handling images. Especially the arbitrary resizing of images is very convenient. Whenever a page is accessed and the image size can’t be found, it will be created on the fly. You can use as many different image sizes as you like, without always having to use plugins like Regenerate Thumbnails when you make a change to the default WordPress image sizes.

Timmy uses Timber’s ImageHelper class to enhance this functionality even more.

Mimicks default WordPress image functionalities

  • You can have as many defined image sizes as you want. It’s easier to work with named image sizes like thumbnail, medium, portrait etc. Timmy lets you define each image size with a lot of handy configuration options.

  • Users can select different image sizes in WYSYWIG editor. Normally, a user can only select the default WordPress sizes Thumbnail, Medium, Large and Full. With images defined through Timmy, a user can select all image sizes that you define, without the default sizes.

  • Makes images inserted into a post’s content via WordPress Editor responsive.

  • Integration for popular plugins like Advanced Custom Fields, Admin Columns and Yoast SEO. Because Timmy tells WordPress that there are image sizes present, other plugins will allow you to select images defined through Timmy, like the preview images for image fields defined with ACF or a preview image used in Admin Columns.

  • You can still use Regenerate Thumbnails. Using Regenerate Thumbnails with Timmy will clean your uploads folder from image sizes you don’t need anymore. If you have no image sizes defined with Timmy, Timmy will delete all image sizes generated with Timmy. But no worries, remember that Timber automatically creates an image size if it doesn’t already exist.

  • You can still use Timber’s resize functions. Timber has some really neat image manipulation functions. You can still use these or you can also use a mix of the two.

Helps you with image HTML output

  • Responsive images. For each image size, you can define additional sizes that will be used for the responsive image srcset.
  • Lazy loading markup. Adds lazy loading markup to your image.
  • Accessibility. Timmy automatically pulls image alt texts and adds them to your image.

Reasonable image generation

  • Image sizes are generated when they are uploaded. When you use Timber images you don’t have to care about image sizes being present in the uploads folder. If your frontend is accessed, Timber creates image sizes when they don’t already exist. You’d always have to visit the frontend to make sure the first visitor of a page doesn’t have really long loading times. Because Timmy knows which sizes you want to use – you defined them – it will generate them for you. There are cases where this is useful, e.g. when some posts are created automatically and you also pull in images.

  • Restrict to post types to prevent bloat. If you want to use an image size just for one post type, you can define that. This will prevent bloating up your uploads folder with image sizes that are never used on the site.

Limitations

  • We don’t know if Timmy works with images hosted on Content Delivery Networks (CDN). We haven’t looked into that yet and we don’t know if we ever will. Pull requests welcome ;).

timmy's People

Contributors

alexwoollam avatar drzraf avatar gchtr avatar github-actions[bot] avatar hanifbirgani avatar luisbraga avatar nlemoine avatar salaros avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

timmy's Issues

Outdated example in documentation?

Hi, just flagging a very minor possible issue in the documentation.

On line 200 of /docs/image-configuration.md the example includes 'resize_srcset' => true - is this an outdated name for the generate_srcset_sizes option?

Do not upscale/overize in filter_image_downsize

Timmy apparently lacks the checks about whether cropping/resizing would actually reduce (contrary to increase) an image during the image_downsize filter (Since neither filter_image_downsize nor resize() contain the oversize guards which only live inside get_image_params()).
That's one such trace I grabbed:

  25 => 
  array (
    'function' => 'post_get_meta_field',
    'type' => 'dynamic',
    'class' => 'Timber\\Integrations\\ACF',
    'file' => '/web/wp/wp-includes/class-wp-hook.php',
    'line' => 289,
    'params' => 
    array (
      'value' => '\'27721\'',
      'post_id' => '27716',
      'field_name' => '\'headerImageMobile\'',
    ),
  ),
  26 => 
  array (
    'function' => 'get_field',
    'file' => '/web/app/plugins/timber-library/lib/Integrations/ACF.php',
    'line' => 30,
    'params' => 
    array (
      'selector' => '\'headerImageMobile\'',
      'post_id' => '27716',
      'format_value' => '???',
    ),
  ),
[.... .... ...]
  33 => 
  array (
    'function' => 'format_value',
    'type' => 'dynamic',
    'class' => 'acf_field_image',
    'file' => 'web/wp/wp-includes/class-wp-hook.php',
    'line' => 287,
    'params' => 
    array (
      'value' => '\'27721\'',
      'post_id' => '27716',
      'field' => '[\'ID\' => 0, \'key\' => \'field_5f7ddcfa8c43d\', \'label\' => \'Header Image Mobile\', \'name\' => \'headerImageMobile\', \'prefix\' => \'acf\', \'type\' => \'image\', \'value\' => NULL, \'menu
_order\' => 1, \'instructions\' => \'com)\'
, \'required\' => 0, \'id\' => \'\', \'class\' => \'\', \'conditional_logic\' => 0, \'parent\' => \'group_5ba3c42472043\', \'wrapper\' => [\'width\' => \'\', \'class\' => \'\', \'id\' => \'\'], \'return_format\' 
=> \'array\', \'preview_size\' => \'thumbnail\', \'library\' => \'all\', \'min_width\' => 1666, \'min_height\' => 3000, \'min_size\' => \'\', \'max_width\' => 1666, \'max_height\' => 3000, \'max_size\' => \'\', \
'mime_types\' => \'jpg,jpeg\', \'_name\' => \'headerImageMobile\', \'_valid\' => 1]',
    ),
  ),
  34 => 
  array (
    'function' => 'acf_get_attachment',
    'file' => 'web/app/plugins/advanced-custom-fields-pro/includes/fields/class-acf-field-image.php',
    'line' => 337,
    'params' => 
    array (
      'attachment' => '27721',
    ),
  ),
  35 => 
  array (
    'function' => 'wp_get_attachment_image_src',
    'file' => 'web/app/plugins/advanced-custom-fields-pro/includes/api/api-helpers.php',
    'line' => 3189,
    'params' => 
    array (
      'attachment_id' => '27721',
      'size' => '\'content-default\'',
      'icon' => '???',
    ),
  ),
  36 => 
  array (
    'function' => 'image_downsize',
    'file' => 'web/wp/wp-includes/media.php',
    'line' => 953,
    'params' => 
    array (
      'id' => '27721',
      'size' => '\'content-default\'',
    ),
  ),
  37 => 
  array (
    'function' => 'apply_filters',
    'file' => 'web/wp/wp-includes/media.php',
    'line' => 207,
    'params' => 
    array (
      'tag' => '\'image_downsize\'',
      'value' => 'FALSE',
      1 => '27721',
      2 => '\'content-default\'',
    ),
  ),
  38 => 
  array (
    'function' => 'apply_filters',
    'type' => 'dynamic',
    'class' => 'WP_Hook',
    'file' => '/web/wp/wp-includes/plugin.php',
    'line' => 212,
    'params' => 
    array (
      'value' => 'FALSE',
      'args' => '[0 => FALSE, 1 => 27721, 2 => \'content-default\']',
    ),
  ),
  39 => 
  array (
    'function' => 'filter_image_downsize',
    'type' => 'dynamic',
    'class' => 'Timmy\\Timmy',
    'file' => '/web/wp/wp-includes/class-wp-hook.php',
    'line' => 287,
    'params' => 
    array (
      'return' => 'FALSE',
      'attachment_id' => '27721',
      'size' => '\'content-default\'',
    ),
  ),
  40 => 
  array (
    'function' => 'resize',
    'type' => 'static',
    'class' => 'Timmy\\Timmy',
    'file' => '/vendor/mindkomm/timmy/lib/Timmy.php',
    'line' => 496,
    'params' => 
    array (
      'img_size' => '[\'resize\' => [0 => 3000], \'srcset\' => [0 => [...], 1 => [...], 2 => [...], 3 => [...], 4 => [...], 5 => [...], 6 => [...], 7 => [...], 8 => [...], 9 => [...], 10 => [...], 11 => [...]], \'sizes\' => \'(max-width: 1200px) 100vw, 1200px\', \'show_in_ui\' => TRUE, \'oversize\' => [\'allow\' => FALSE, \'style_attr\' => FALSE], \'name\' => \'Content - Default\']',
      'file_src' => '\'https://bar.mx/app/uploads/2021/02/foo-3-mx.jpg\'',
      'width' => '3000',
      'height' => '0',
      'crop' => '\'default\'',
      'force' => 'FALSE',
    ),
  ),
  41 => 
  array (
    'function' => 'resize',
    'type' => 'static',
    'class' => 'Timber\\ImageHelper',
    'file' => '/vendor/mindkomm/timmy/lib/Timmy.php',
    'line' => 698,
    'params' => 
    array (
      'src' => '\'https://bar.mx/app/uploads/2021/02/foo-3-mx.jpg\'',
      'w' => '3000',
      'h' => '0',
      'crop' => '\'default\'',
      'force' => 'FALSE',
    ),
  ),

uploads/2021/02/foo-3-mx.jpg is actually 1666x3000 and Timmy must know about this. Then it must not try to create an image larger than the initial one since it's has all the chances to end-up badly:

  • Because the resulting image bring no quality (Browser can upscale image if told so and do it quicker and better)
  • Because triggering imagick to upscale often lead to memory problems (Among those ran by web/wp/wp-includes/class-wp-image-editor-imagick.php many filters would consume a bunch of memory on bigger images).

Class 'Timmy\Image' not found when using v1.0

Today i gave the v1.0 a spin but i get the following error:
Fatal error: Uncaught Error: Class 'Timmy\Image' not found in /var/www/html/wp-content/plugins/timmy-1.0.0/lib/Timmy.php:161 Stack trace: #0 /var/www/html/wp-content/themes/yk/template-home.php(10): Timmy\Timmy::get_image(260, 'nocrop') #1 /var/www/html/wp-includes/template-loader.php(106): include('/var/www/html/w...') #2 /var/www/html/wp-blog-header.php(19): require_once('/var/www/html/w...') #3 /var/www/html/index.php(17): require('/var/www/html/w...') #4 {main} thrown in /var/www/html/wp-content/plugins/timmy-1.0.0/lib/Timmy.php on line 161

I installed Timmy as a plugin without composer and initialized Timmy (simplified) as follows:

use Timmy\Timmy;
Timmy::init();
$image = Timmy::get_image(260, 'nocrop');

When taking a look at Timmy.php is see the following:

$class = apply_filters( 'timmy/image/class', Image::class );
$size_array = $size;

if ( is_string( $size ) ) {
if ( in_array( $size, [ 'full', 'original' ], true ) ) {
	$size_array = [];
} else {
	$size_array = Helper::get_image_size( $size );
}
}
$image = $class::build( $attachment, $size_array );

The last line is line 161

Is there anything else i can try to debug this issue?

Timmy version: 1.0
Timber version: 1.22.1

When the timmy/generate_srcset_sizes is set to true the 'oversize' option is ignored

I stumbled across an issue with the timmy/generate_srcset_sizes hook.
When set to true, the system will automatically generate all responsive sizes. This works perfect, but not if you have the following oversize configuration:

'oversize' => array( 'allow' => false, 'style_attr' => false )
It should not generate sizes bigger than the source image, but it does.
The function (generate_srcset_size, timmy.php, r864) which generates the sizes doesn't check the oversize settings.
As a temporary workaround i did the following, which fixes it for now.

rule 904:

// Generate additional image sizes used for srcset.
if (isset($img_size['srcset'])) {
    foreach ($img_size['srcset'] as $srcset_size) {
        list($width, $height) = Helper::get_dimensions_for_srcset_size(
            $img_size['resize'],
            $srcset_size
        );
        
        // hacky fix to make sure that we are not generating image sizes
        // which are bigger that the max size of the image

        // create a cloned version of the $img_size array
        $cloned_img_size = $img_size;
        // add the "to be created" size
        $cloned_img_size['resize'] = array($width,$height);

        // put the img_size through the get_image_params function to make sure
        // it is checked against the "oversize" settings.
        // $width and $height will be overriden by the list() helper
        list(
            $file_src,
            $width,
            $height,
        ) = Timmy::get_image_params($timber_image, $cloned_img_size);
        
        // For the new source, we use the same $crop and $force values as the default image.
        self::resize($img_size, $file_src, $width, $height, $crop, $force);
    }
}

Thanks for your work!

Fatal error: Uncaught Error: Call to undefined function Timmy\add_action()

Hey guys,

Love your work. I'm having trouble getting Timmy working on my installation.
I have installed Timmy and Timber both via Composer, the latest versions of both.

In function.php I have the autoloader set, however it seems Timmy is loaded before the wp functions are available?

Here's the full error:


( ! ) Fatal error: Uncaught Error: Call to undefined function Timmy\add_action() in /Users/nick/Sites/xx/vendor/mindkomm/timmy/lib/Timmy.php on line 19
( ! ) Error: Call to undefined function Timmy\add_action() in /Users/nick/Sites/xx/vendor/mindkomm/timmy/lib/Timmy.php on line 19
Call Stack
#	Time	Memory	Function	Location
1	0.0001	370528	{main}( )	.../index.php:0
2	0.0001	370816	require( '/Users/nick/Sites/xx/www/wp/wp-blog-header.php' )	.../index.php:5
3	0.0001	371168	require_once( '/Users/nick/Sites/xx/www/wp/wp-load.php' )	.../wp-blog-header.php:13
4	0.0002	371944	require_once( '/Users/nick/Sites/xx/www/wp-config.php' )	.../wp-load.php:42
5	0.0002	373712	require_once( '/Users/nick/Sites/xx/vendor/autoload.php' )	.../wp-config.php:7
6	0.0004	389808	ComposerAutoloaderInit89b2a1fa8ec074114b3ea6f13e74d114::getLoader( )	.../autoload.php:7
7	0.0015	579048	composerRequire89b2a1fa8ec074114b3ea6f13e74d114( )	.../autoload_real.php:56
8	0.0015	579720	require( '/Users/nick/Sites/xx/vendor/mindkomm/timmy/init.php' )	.../autoload_real.php:66
9	0.0021	667432	Timmy\Timmy->__construct( )	.../init.php:7
10	0.0028	780264	Timmy\Timmy->init( )	.../Timmy.php:13

resize to height not generating images

Hi, if i do this:

'srcset'     => array(
                2,
                array(0, 300),
                array(0, 600),
                array(0, 400),
                array(0, 800),
                array(0, 750),
                array(0, 1500)
            ),

It does not work, in timber if i use the resize filter it does work..

Undefined index: file_src when uploading file

Hi,

I've encountered an issue with Timmy regarding the generating of "resizes".
When i upload an image i get the following error and the resizes are not generated.

Notice: Undefined index: file_src in /var/www/html/wp-test/wp-content/plugins/timmy-0.14.4/lib/Timmy.php on line 867

I am using the following configuration in a fresh WP install (v5.4.1) with the latest version of [email protected] and [email protected].

if (class_exists('Timmy\Timmy')) {
    new Timmy\Timmy();
}

// reset thumbs sizes
set_post_thumbnail_size(0, 0);

// set Timmy sizes
add_filter('timmy/sizes', function ($sizes) {
    return array(
        'custom-4' => array(
            'resize' => array( 370 ),
            'srcset' => array( 2 ),
            'sizes' => '(min-width: 992px) 33.333vw, 100vw',
            'name' => 'Width 1/4 fix',
            'post_types' => array( 'post', 'page' ),
        ),
    );
});

// prevent wordpress downscaling image
add_filter('big_image_size_threshold', '__return_false');
// generate all sizes upon upload
add_filter('timmy/generate_srcset_sizes', '__return_true');

I'm tracking down the issue and it seems that the following function does not return a 'file_src' attribute, but it does supply a 'file' attribute.

File: Timmy.php, line: 867

// Get unfiltered meta data to prevent potential recursion.
$meta_data = wp_get_attachment_metadata($attachment->ID, true);
$file_src  = $meta_data['file_src'];

But 'file' does not contain an absolute path to the image which the resize function demands. This results in the system skipping the "resizes".

I've encountered this on an existing setup as well, that's why i made a fresh install within a production environment to double check and skip potential php errors.

Does anyone else encounter this?

Uninitialized string offset: 0 error

I copied some code from an old project with timmy (which works perfect, thanks so much for this great package!). But in a new project it's giving me this (non-descriptive) error an dI'm not sure what the cause of it could be:

Notice: Uninitialized string offset: 0 in /Users/flowflow/_DATA/DOCUMENTS/_htdocs/_MAMP_htdocs/guildconferences.com/wp-content/plugins/timmy-0.14.1/lib/Helper.php on line 110

Any pointers?

Timmy tries to resize video files

I just ran into an issue where Timmy was trying to resize video files with ffmpeg. Is that expected?
This ended up creating multiple ffmpeg processes that were filling /tmp with magick-* files and filling up memory, resulting in a server crash.

This is what the ffmpeg cmd lines looked like:

> sh -c 'ffmpeg' -nostdin -v -1 -i '/tmp/magick-8802W6_GtpP7yVaH' -vframes 2147483647 -vcodec pam -an -f rawvideo -y '/tmp/magick-8802l3NLfb57smfV.pam' 2> '/tmp/magick-8802l3NLfb57smfV'
> ffmpeg -nostdin -v -1 -i /tmp/magick-8802W6_GtpP7yVaH -vframes 2147483647 -vcodec pam -an -f rawvideo -y /tmp/magick-8802l3NLfb57smfV.pam

I saw this error in wp-content/debug.log:

[ Timber ] WP_Error Object
(
    [errors] => Array
        (
            [image_save_error] => Array
                (
                    [0] => delegate failed `'ffmpeg' -nostdin -v -1 -i '%M%%d.jpg' '%u.%m' 2> '%u'' @ error/delegate.c/InvokeDelegate/1949
                )

        )

    [error_data] => Array
        (
            [image_save_error] => .../some-file-150x150-c-default.mp4
        )

    [additional_data:protected] => Array
        (
        )

)

This is not something I would expect to happen.

Regenerate thumbnails throws errors when timmy is enabled

After enabling Timmy if I try to run regnerate thumbnails it gives this error for all attachments:

Skipped Attachment ID 42: SyntaxError: Unexpected token < in JSON at position 0

When inspecting the network activity from the browser I see that it try to get one "json" by attachament and it gives some notices, which are printed by xdebug, which in turn it eventually make the json invalid.

Here are some of the notices printed:

Notice: Undefined index: width in /.../wp-content/plugins/regenerate-thumbnails/includes/class-regeneratethumbnails-regenerator.php on line 626
...


12 | 0.1174 | 12462976 | RegenerateThumbnails_REST_Controller->regenerate_item( ) | .../class-wp-rest-server.php:936
-- | -- | -- | -- | --
13 | 2.7582 | 15143840 | RegenerateThumbnails_REST_Controller->attachment_info( ) | .../class-regeneratethumbnails-rest-controller.php:206
14 | 2.7582 | 15144384 | RegenerateThumbnails_Regenerator->get_attachment_info( ) | .../class-regeneratethumbnails-rest-controller.php:226

There is also the same notice for the indexes height and crop

Thumbnail not recognised and Unknown "get_timber_image_responsive"

I followed the steps mentioned in the readme file, namely I installed Timber and Timmy, reset every image size to 0 in Media Settings and placed the following on my functions file:

// We are resetting default image sizes so that we can override them with a
// Timmy, a more convenient way to work with images and Timber
set_post_thumbnail_size(0, 0);

function gwm_remove_default_image_sizes( $sizes) {
    unset( $sizes['shop_thumbnail']);
    unset( $sizes['shop_catalog']);
    unset( $sizes['shop_single']);
    return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'gwm_remove_default_image_sizes');


// Set the new images sizes to be used in twig templates
function get_image_sizes() {
    return array(
        'thumbnail' => array(
            'resize' => array( 150, 150 ),
            'name' => 'Thumbnail',
            'post_types' => array( 'all' ),
        ),
        'custom-4' => array(
            'resize' => array( 370 ),
            'srcset' => array( 2 ),
            'size' => '(min-width: 992px) 33.333vw, 100vw',
            'name' => 'Width 1/4 fix',
            'post_types' => array( 'post', 'page', 'product' ),
        ),
    );
}

However when I go to the media center in the Dashboard, WordPress is loading the full size of the images as thumbnails, which makes me believe it isn't running the above function. Do I need to hook it up to any WordPress action?

In the front-end, im also getting the following errors:

Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'Unknown "get_timber_image_responsive" filter in "products/parts/product-tile.html" at line 18.' in /Users/luismartins/Sites/project.dev/wp-content/plugins/timber-library/vendor/twig/twig/lib/Twig/ExpressionParser.php on line 601

and

Twig_Error_Syntax: Unknown "get_timber_image_responsive" filter in "products/parts/product-tile.html" at line 18. in /Users/luismartins/Sites/hydracheck.dev/wp-content/plugins/timber-library/vendor/twig/twig/lib/Twig/ExpressionParser.php on line 601

which lead me to believe Timmy isn't being recognised at all. Am I missing some step?

get_timber_image_responsive_acf doesn't deliver image but error message

Hi,

if I use the function get_timber_image_responsive_acf in my twig files like this:
<img class="" {{ get_timber_image_responsive_acf('image_file', 'blog-post-full') }}>

I get following notice:

Notice: Trying to access array offset on value of type int in \mindkomm\timmy\functions-images.php on line 452
src=“ sizes="(min-width: 43rem) 860px, 100vw" srcset="//localhost:3000/app/uploads/2020/04/img-375×0-c-default.jpg 375w, //localhost:3000/app/uploads/2020/04/img-500×0-c-default.jpg 500w, //localhost:3000/app/uploads/2020/04/img-750×0-c-default.jpg 750w, //localhost:3000/app/uploads/2020/04/img-800×0-c-default.jpg 800w, //localhost:3000/app/uploads/2020/04/img-860×0-c-default.jpg 860w, //localhost:3000/app/uploads/2020/04/img-1000×0-c-default.jpg 1000w, //localhost:3000/app/uploads/2020/04/img-1125×0-c-default.jpg 1125w, //localhost:3000/app/uploads/2020/04/img-1500×0-c-default.jpg 1500w, //localhost:3000/app/uploads/2020/04/img-1800×0-c-default.jpg 1800w, //localhost:3000/app/uploads/2020/04/img-2100×0-c-default.jpg 2100w, //localhost:3000/app/uploads/2020/04/img-2400×0-c-default.jpg 2400w" 
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"“ alt=““ title=““>

The image does not show, the HTML looks like this: <img class="" <br="">

When using this instead: <img class="" {{ Image(fields.image_id)|get_timber_image_responsive('blog-post-full') }}> it works perfectly.

Is it just me or did anyone encounter this problem as well?

Timmy stopped working after Upgrade

On a project I'm working on we recently upgraded Timmy from 0.13.6 to 0.14.0 and Timmy stopped working all together as far as I can tell.

We have installed:
timber/timber: 1.1
mindkomm/timmy: 0.14.0
kint-php/kint-twig: 2.0

Are there any known issues with these packages?

Resizing gone wrong since Timber 1.2.3

The TimberImage->src() method got refactored to use wp_get_attachment_url(). This returns the url of the thumbnail as a default. Which results in resizing the wrong image.

For example:
/uploads/doge-150x150-c-default-1200x0-c-default.jpg

See my comment: timber/timber@2b0c06a

Changing

$file_src   = $timber_image->src();

to

$file_src   = $timber_image->src('original');

in Timmy.php line 314 fixes it for now.

Running filters during upload

Hello,

I wonder if it's possible to run a filter and/or custom filter when defining sizes? Apologies if I have missed this in the documentation.

        'image-article_small' => array(
            'show_in_ui' => false,
            'resize' => array(640, 350, 'center'),
            'name' => 'Image article small',
        ),

Something like

        'image-article_small' => array(
            'show_in_ui' => false,
            'resize' => array(640, 350, 'center'),
            'webp' => true, // Uses the same towebp filter that comes with timber
            'filters' => array('my_custom_filter '), // Uses a custom filter added to twig
            'name' => 'Image article small',
        ),

No worries if this doesn't exist, as towebp does of course crunch the images upload first visit, and so should a custom filter. Just trying to achieve best possible performance.

lazy_src in picture_responsive

Hi!
Thanks for this super nice project.
I'm currently thinking of updating my current project to make use of timmy in version 1.0.0 beta 2 (I absolutely want to take advantage of webp and the picture format).
I am using a JS lib and I ran into an issue with the lazy parameters : the parameters to force prepend data- to the various attributes does not seem to work in the context of the picture_responsive (lazy_srcset: true, lazy_src: true, lazy_sizes: true).

Is this something you could take care of?

Thanks a lot for your help and for this hard work, it really is a nice addition to Timber.

Have a nice day!

Media Library Thumbnail Size not working

Hello!

I have a question about the image size in the Media Library.
Is it possible that the plugin also affects the thumbnail size in the backend? Currently, images are no longer reduced and always included in full size.

What could be the reason for this?

screenshot_ 2021-06-15_11-55-39

My config:

add_filter("timmy/sizes", function ($sizes) {
    return array(
        "thumbnail" => array(
            "resize" => array(150, 150),
            "srcset" => array(
                25,
                15,
                10,
            ),
            "name" => "Thumbnail",
            "post_types" => array("all"),
        ),
        "medium" => array(
            "resize" => array(240, 240),
            "name" => "Medium",
            "post_types" => array("all"),
        ),
        "medium_large" => array(
            "resize" => array(768),
            "name" => "Medium Large",
            "post_types" => array("all"),
        ),
        "large" => array(
            "resize" => array(1920, 1080),
            "name" => "Large",
            "post_types" => array("all"),
        ),
        "landscape" => array(
            "resize" => array(32, 20, "center"),
            "name" => "Landscape",
            "srcset" => array(
                80,
                60,
                45,
                35,
                25,
                15,
                10,
            ),
            "post_types" => array("all"),
        ),
        "panorama" => array(
            "resize" => array(32, 12),
            "name" => "Panorama",
            "srcset" => array(
                80,
                60,
                45,
                35,
                25,
                15,
                10,
            ),
            "post_types" => array("all"),
        ),
        "portrait" => array(
            "resize" => array(28, 36, "bottom"),
            "name" => "Portrait",
            "srcset" => array(
                80,
                60,
                45,
                35,
                25,
                15,
                10,
            ),
            "post_types" => array("all"),
        ),
        "custom" => array(
            "resize" => array(24, 30, "bottom"),
            "name" => "Portrait",
            "srcset" => array(
                80,
                60,
                45,
                35,
                25,
                15,
                10,
            ),
            "post_types" => array("all"),
        ),
        "square" => array(
            "resize" => array(20, 20, "center"),
            "srcset" => array(
                80,
                60,
                45,
                35,
                25,
                15,
                10,
            ),
            "name" => "Square",
            "post_types" => array("all"),
        ),
        "auto" => array(
            "resize" => array(30),
            "srcset" => array(
                array(2560),
                array(1920),
                array(1400),
                array(1100),
                array(800),
                array(500),
                array(300),
            ),
            "name" => "Auto",
            "post_types" => array("all"),
        ),
    );
});

How to allow custom image size or disable custom image size within admin

I have an existing project that I'm converting to Timmy. The site editors have used the custom image size feature when adding posts.

image

After switching to Timmy these images no longer work and I'm trying to figure out the best solution. Do I have to force the editors to use the predefined image sizes (and if so is there a way to remove the custom image size option from the admin) or is it possible to tell Timmy to generate the image when someone uses a custom size?

Notice: Trying to access array offset on value of type bool in mindkomm/timmy/lib/Image.php on line 499

That line is $this->max_width = $this->meta['width']

My Timber templates contain things like:
srcset="{{ bg_image_landscape|get_timber_image_srcset('hero') }}"

And this is the tail of the stack when this happens:

15 | 0.4629 | 16296816 | get_timber_image_srcset( $timber_image = 27465, $size = 'hero', $args = ??? ) | .../Environment.php(497) : eval()'d code:93
16 | 0.4655 | 16301776 | Timmy\Image->srcset( $args = [] ) | .../functions-images.php:70
17 | 0.4655 | 16302152 | Timmy\Image->width(  ) | .../Image.php:342
18 | 0.4656 | 16302528 | Timmy\Image->max_width(  ) | .../Image.php:538

Support wordpress loading="lazy" feature (since 5.5)

We updated our wordpress recently to 5.5 mainly because we want to make use of the lazy loading attribute which wordpress can now add automatically.

I know Timmy supports lazy loading with JS, but is it planned to support the browser native loading attribute?

Thanks a lot!

How to handle "simple" retina images

On some website it is sometimes useful to have an image preset with just a retina version. For example a profile thumb with default of 100x100 and a retina version of 200x200.

Ideally we should be able to return something like:

<img srcset="normal.jpg 1x, retina.jpg 2x" .. />

It seems that currently Timmy only output the image 'w'. So I tried to create 2 image presets and use that to render a picture element. The presets would look like this:

'card' => [
    'resize' => [100, 100],
  ],
  'card@2x' => [
    'resize' => [200, 200],
  ],

And then render them with something like this:

return '<picture>
  <source ' . get_timber_image_responsive_src($image, $preset . '@2x') . ' media="(min-device-pixel-ratio: 1.5), (min-resolution: 144dpi)">
  <source ' . get_timber_image_responsive_src($image, $preset) . '>
  <img srcset="' . get_timber_image_src($image, $preset) . '" alt="' . $image['alt'] . '"' . $attributes_str .' />
</picture>';

This gives us:

<picture>
  <source src="unsplash-200x200-c-default.jpg" media="(min-device-pixel-ratio: 1.5), (min-resolution: 144dpi)">
  <source src="unsplash-100x100-c-default.jpg">
  <img srcset="unsplash-100x100-c-default.jpg" alt="">
</picture>

Notice that the source elements have an src element and not an srcset. Eventually chrome and firefox and probably other browser doesn't seem to support src attributes on the source element. Only the standard image is loaded, even on retina display.

The use of src instead of srcset if there is only one url is defined here: https://github.com/mindkomm/timmy/blob/master/functions-images.php#L319

PHP warning in timber_should_resize

I am getting a PHP warning in the following function on the line marked '<-- HERE' because $parent is empty/null:

  private function timber_should_resize( $attachment_parent_id, $img_size ) {
    /**
     * Normally we don’t have a post type associated with the attachment
     *
     * We use an empty array to tell the function that there is no post type
     * associated with the attachment.
     */
    $attachment_post_type = array( '' );

    // Check if image is attached to a post and sort out post type.
    if ( 0 !== $attachment_parent_id ) {
      $parent               = get_post( $attachment_parent_id );
      $attachment_post_type = array( $parent->post_type ); // <-- HERE
    }

    return self::is_size_for_post_type( $img_size, $attachment_post_type );
  }

I'm not sure exactly why the attachment parent ID is invalid for the photo. The image is used in an ACF image field, so it's not attached to a particular post. When I try to find the post corrresponding to the attachment parent ID, WordPress tells me that maybe it was deleted.

Responsive remote/external/CDN image

I implement to work on this soon.

Current use case: I copy/paste Gutenberg page from one site to another. The markup reference the original image but the generated srcset attributes are wrong (because my render_block hooks consider the ID of files which are not present in the destination instance).

My plan is to use get_timber_image_responsive_src (which is my current entrypoint inside the library) to check whether a file is local or remote.

My rough plan from here is:

  1. Timmy::get_image() would detect it's an external/remote file URL and if yes, return an instance of \Timmy\RemoteImage (subclass of \Timmy\Image)
  2. Timmy\RemoteImage would mostly override srcset() which would check over http for the possibly existing derivative images. If some happen to exist then cache the result of the (in)existence inside a transient.
  3. Generate the adequate srcset attribute.

This assume the size attribute passed to get_timber_image_responsive_src at destination WP instance is equal to the one passed at source WordPress instance (or at least that the resulting URL paths match).

Optional (for me): If the URL match known/supported CDN hostname, use its particular API to fetch the variations. (Cloudflare cdn-cgi & co)

Your thoughts?

Cannot use timmy responsive content images with wordpress responsive images in combination

Currently as a theme editor i need to if i want to use the reponsive content images from timmy or if wordpress should make the images reponsive.

With timmy we can define the reponsiveness of content images in a way more detailed way (as it should be) but it only works if the content editor manually selects the correct image size, which has the inherent risk that a content editor just does not do it for whatever reason which ends up with non optimized images.

On the other hand wordpress can automatically make images reponsive but in a very unflexible way which is basically only helpful for full width images like the cover block.

But as full width images like the cover block are several times larger than other content images those are the most important parts when it comes to repsonsive images.

Until wordpress implements responsive images which a theme editor can really configure i think, in the case where it is not sure that the content editors are always setting the correct image sizes, the best workaround would be:

  1. for normal use cases like 1 or 2 columned images in the post content use timmy, if the editor does not set the correct image size it does not hurt so much
  2. for very important images like the fullscreen cover let wordpress automatically make the image responsive to be sure it is not leave unoptimized

Currently this is not achievable because timmy disables the wordpress reponsive image feature when opting in to the timmy reponsive image feature.

I dont know if there is a good way to make them work together and let wordpress do the optimization stuff if timmy is not finding the correct size.

But at least i wanted to make aware of the situation. Maybe there are other good solutions as well.

Thanks!

Inline Styles

Is it possible to remove the inline style that gets added for width?

ACF Field preview image returns thumbnail-size after selecting

I've created an ACF image field and set the preview image to a landscape size defined in the Timmy configuration.

When i click "select image" and select an image in the Media Library it seemed the wrong preview image size was returned, because the preview showed a thumbnail size. After saving the post and returning to the ACF field it worked perfectly and it showed the right size.

When inspecting the AJAX request upon selecting the image i saw that the src of the different media sizes were all set to the thumbnail size. Searching through the Timmy code i stumbled upon the part which caused this and it's a feature to prevent the system from unnecessarily creating many image sizes on the fly. For now i disabled that part of the code because i pre generate all the image sizes.

Does anyone encounter the same behaviour? is it something to get used to or can we somehow create a workaround? Because i really like the way this plugin enables me to deal with responsive images.

Installed using Composer
Timmy: 0.14.0
Timber: 1.9.4
Wordpress: 5.1.1

Timmy.php Line:291

/**
 * Return thumbnail size when media files are requested through an AJAX call.
 *
 * When image data is prepared for the Media view, WordPress calls 'image_size_names_choose'
 * to get all selectable sizes for the backend and then 'image_downsize' to get all the
 * image data. All image sizes that don’t exist yet would be generated, which probably
 * causes a max execution timeout error.
 *
 * We make sure that for the Media view, we only return the thumbnail size for an image. If
 * the thumbnail size doesn’t exist yet, it is generated.
 *
 *
 * @see   wp_prepare_attachment_for_js()
 * @since 0.12.0
 */
if ( 'query-attachments' === $action ) {
	
	$thumbnail_size = Helper::get_thumbnail_size();

	list( $width, $height ) = Helper::get_dimensions_for_size( $thumbnail_size );

	$crop  = Helper::get_crop_for_size( $thumbnail_size );
	$force = Helper::get_force_for_size( $thumbnail_size );

	// Resize to thumbnail size
	$src = self::resize( $thumbnail_size, $file_src, $width, $height, $crop, $force );
	//echo $src;
	/**
	 * Get original dimensions for a file that are used for the image data and the select
	 * input when an image size can be chosen in the backend.
	 *
	 * The src is still the thumbnail size, so that it doesn’t trigger a resize.
	 */
	$original_size = Helper::get_image_size( $size );

	list( $width, $height ) = Helper::get_dimensions_for_size( $original_size );

	return array( $src, $width, $height, true );
}

Breaks Yoast SEO og:image

Issue
The removal of the image sizes automatically generated when uploading an image done here makes the wordpress function image_get_intermediate_size() always return the full size image. However, if the full size image is wider or higher than 2000px, Yoast SEO rejects it as an og:image. It would therefore be great, if the image size large would not be cleared out. Or the function would at least have a filter.

Yoast SEO uses the image_get_intermediate_size() function here.

How to reproduce it
Prerequisites: WordPress with Theme that uses Timmy and the Yoast SEO Plugin.

Create a post, navigate to the social section of Yoast SEO metabox and add a facebook image that is wider than 2000px. Visit the post (frontend) and inspect the source code. The meta property og:image is missing.

Then change the image to one that is smaller than 200px wide and inspect the source code again -> the meta property og:image is now here.

How do you handle derivative image path pattern(s)

Hi, sorry for the support issue. I'm switching to Timmy and formalize my thumbnail size but hit a couple of issues.

I've an hundred of posts referencing derivative images (whether within ACF whether in the post_content). All these will break as a soon as I switch to Timmy (and regenerate thumbnails / purge old derivative files) because the filename pattern changes from, eg, image-A-300x252.png to image-A-300x0-c-default.png.

  1. It's far from future-proof, how do you handle this situation?
  2. Do you know about existing WP bugreports related to this (and the lack of an intermediary and height/width-agnostic representation of inlined images)?
  3. Is there a foolproof method/hook to store derivative images in completely different upload subfolder (to make identification of their references within the database easier)?
  4. And if yes, would you think using the format name instead of actual dimension for filename could be a realistic way to solve this, eg, image-A-medium.png?

Focal point for crop coordinates

Hi,

This looks like a very, very useful addition to Timber.
One thing I've struggling with Timber's images is a way to better control cropping. With standard WordPress images, you can use something like https://wordpress.org/plugins/my-eyes-are-up-here/ which is absolutely brilliant for that. Unfortunately this doesn't work for Timber's arbitrary cropping sizes. Do you have any plans for something similar?

Compatibility with Composer-installed Timber

Now that Timber is recommending installation via Composer, it would be great if we could also install Timmy that way. Or, if that is not possible for some reason, if Timmy were at least compatible with Timber installed via Composer.

Right now, with Timber installed via Composer and Timmy installed as a WP plugin, I get the following error:

Fatal error: Uncaught Twig_Error_Syntax: Unknown "get_timber_image_responsive" filter in "page.twig" at line 6. in /var/www/wp-content/themes/themename/vendor/twig/twig/lib/Twig/ExpressionParser.php on line 605

It looks like with this configuration, Timber parses the templates before Timmy has hooked in its custom filters. I'll keep installing Timber as a plugin for the time being (Timmy is just too good to give up), but I do like the idea of keeping them as dependencies of the theme, rather than installed plugins, since they are really only useful & necessary for the particular theme I am using them on.

Thanks for considering!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.