你说得对,图像处理类不支持这样做。
但是,您可以扩展库(底部为http://codeigniter.com/user_guide/general/creating_libraries.html),并根据您已找到的链接添加新方法。
在这里,我的工作很无聊,延长CI的图像处理lib和添加这个方法:
public function trim_whitespace($color = 'FFFFFF')
{
//load the image
$img = $this->image_create_gd();
//find the size of the borders
$b_top = 0;
$b_btm = 0;
$b_lft = 0;
$b_rt = 0;
//top
for(; $b_top < imagesy($img); ++$b_top) {
for($x = 0; $x < imagesx($img); ++$x) {
if(imagecolorat($img, $x, $b_top) != '0x'.$color) {
break 2; //out of the 'top' loop
}
}
}
//bottom
for(; $b_btm < imagesy($img); ++$b_btm) {
for($x = 0; $x < imagesx($img); ++$x) {
if(imagecolorat($img, $x, imagesy($img) - $b_btm-1) != '0x'.$color) {
break 2; //out of the 'bottom' loop
}
}
}
//left
for(; $b_lft < imagesx($img); ++$b_lft) {
for($y = 0; $y < imagesy($img); ++$y) {
if(imagecolorat($img, $b_lft, $y) != '0x'.$color) {
break 2; //out of the 'left' loop
}
}
}
//right
for(; $b_rt < imagesx($img); ++$b_rt) {
for($y = 0; $y < imagesy($img); ++$y) {
if(imagecolorat($img, imagesx($img) - $b_rt-1, $y) != '0x'.$color) {
break 2; //out of the 'right' loop
}
}
}
//copy the contents, excluding the border
$newimg = imagecreatetruecolor(
imagesx($img)-($b_lft+$b_rt), imagesy($img)-($b_top+$b_btm));
imagecopy($newimg, $img, 0, 0, $b_lft, $b_top, imagesx($newimg), imagesy($newimg));
// Output the image
if ($this->dynamic_output == TRUE)
{
$this->image_display_gd($newimg);
}
else
{
// Or save it
if (! $this->image_save_gd($newimg))
{
return FALSE;
}
}
}
用法:
// load extended image lib
$this->load->library('image_lib');
// configure image lib
$config['image_library'] = 'gd2';
$config['source_image'] = 'path/to/source.img';
$config['new_image'] = 'path/to/output.img';
$this->image_lib->initialize($config);
$this->image_lib->trim_whitespace('38ff7e'); // set colour to trim, defaults to white (ffffff)
$this->image_lib->clear();
值得一提的是,即使它会工作,你真的不应该使用这个作为dynamic_output,做保存修剪,否则它只会放慢一切。此外,它只是寻找1个颜色值(尽管这是来自您发布的代码的限制,可能会有更好的功能),所以如果它是一个压缩的jpg,您可能无法获得所有的空白。
感谢您的帮助......我对我应该怎么称呼图像和的时候有点困惑。我应该运行我在那里,然后成功上传运行操作类吗?如果是,那么我应该将它上传到一个临时文件夹,然后运行操作类,将它移动到正确的文件夹?谢谢你的帮助 – Claremont 2012-03-07 21:42:44
是的,当上传成功时,在你的else {}中运行操作。我不确定是否有任何理由在两者之间使用额外的临时文件夹,除非您需要将未更改的图像保存在其他地方。如果您将image_lib的source_image设置为您的upload_path +在$ this-> upload-> data()和new_image中返回的'file_name',它将会覆盖最初上传的文件。 – Tjkoopa 2012-03-08 09:17:51