我正在尝试将大图像拆分为较小的tile。我尝试使用PHP ImageMagick cropImage()
,我可以用以下代码成功地做到这一点。
for($w = 0; $w < ($large_image_width/$tile_width); $w++){
for($h = 0; $h < ($large_image_height/$tile_height); $h++){
$X = $w*$tile_width;
$Y = $h*$tile_height;
$image = new Imagick($input_file);
$image->cropImage($tile_width,$tile_height, $X,$Y);
$image->writeImage("X" . ($w+1) . "Y" . ($h+1) . ".jpg");
}
}
但是它循环遍历每个平铺大小并一次又一次地加载图像。
当我做了更多的研究,我发现了这个链接,这是一个使用命令行的一行。
convert -crop $WIDTHx$HEIGHT@ huge_file.png tile_%d.png
我想知道PHP ImageMagick扩展是否有任何功能来做同样的事情。我也很乐意切换到Perl或其他库,如GD。
您可以通过加载一次映像,然后克隆对象来减少$input_file
I/O。
$source_image = new Imagick($input_file);
for($w = 0; $w < ($large_image_width/$tile_width); $w++){
for($h = 0; $h < ($large_image_height/$tile_height); $h++){
$X = $w*$tile_width;
$Y = $h*$tile_height;
$image = clone $source_image;
$image->cropImage($tile_width,$tile_height, $X,$Y);
$image->writeImage("X" . ($w+1) . "Y" . ($h+1) . ".jpg");
}
}
您还可以优化&减少for循环,或者直接调用一行。
system("convert -crop $WIDTHx$HEIGHT@ $input_file tile_%d.png");
libvips现在有一个PHP绑定,它可以很快地完成这个任务,只使用少量的内存。
例如:#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
use Jcupitt'Vips;
$im = Vips'Image::newFromFile($argv[1]);
$im->dzsave($argv[2], ["overlap" => 0, "tile-size" => 256, "depth" => "one"]);
在这台10k x 10k jpeg图像的笔记本电脑上,我看到:
$ time ./try260.php ~/pics/wtc.jpg x
real 0m2.262s
user 0m3.596s
sys 0m1.256s
在x_files
中创建了1369个jpeg文件:
$ ls x_files/0/ | wc
1369 1369 14319
这里有一篇关于dzsave
操作符的博文(这里使用的是libvips的东西):