-
Notifications
You must be signed in to change notification settings - Fork 4
Description
Hello! I'm the libvips maintainer. This is very cool!
I had a couple of suggestions after looking through the code that could improve performance and drop memory use.
Use thumbnail
, if you can
I would use thumbnail
, if possible. It's much, much quicker than newFromBuffer
and resize
, especially for large reductions on JPG images, and will give higher quality results too, since it will automatically premultiply PNG alpha for you.
For example, I think this is roughly what you are doing at the moment:
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
use Jcupitt\Vips;
# disable vips caching
Vips\Config::cacheSetMax(0);
for ($i = 0; $i < 100; $i++) {
$contents = file_get_contents($argv[1]);
$image = Vips\Image::newFromBuffer($contents);
$target_width = 256;
$image = $image->resize($target_width / $image->width);
$out = $image->writeToBuffer(".jpg");
}
If I run this on my laptop with a 6k x 4k JPG image, I see:
$ /usr/bin/time -f %M:%e ./try275.php ~/pics/theo.jpg
135168:18.91
ie. 135MB of memory, 19s of CPU. If I change it to be:
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
use Jcupitt\Vips;
# disable libvips caching
Vips\Config::cacheSetMax(0);
for ($i = 0; $i < 100; $i++) {
$image = Vips\Image::thumbnail($argv[1], 256);
$out = $image->writeToBuffer(".jpg");
}
I see:
$ /usr/bin/time -f %M:%e ./try276.php ~/pics/theo.jpg
51704:4.69
So 50MB of memory, under 5s of CPU.
You are cropping before resize, which you can't do with thumbnail. I would use thumbnail anyway, and crop afterwards using scaled down coordinates.
Disable caching
By default, libvips will cache the last 1,000 operations or so. This is usually great for performance, but you are not going to be repeatedly operating on the same image, so it is likely to bloat memory for no gain.
I would add:
Vips\Config::cacheSetMax(0);
To your startup code.
If I remove that line from try275.php
(the non-thumbnail version above) I see:
$ /usr/bin/time -f %M:%e ./try275.php ~/pics/theo.jpg
213140:18.65
An extra 90MB of memory used for no speedup.