【问题标题】:Image compress in Codeigniter3Codeigniter 3 中的图像压缩
【发布时间】:2020-09-29 06:14:35
【问题描述】:

我有一段代码通过 Codeigniter gd2 库压缩图像。然而,它变成了这张照片

进入这个

因为我在代码中设置了宽度和高度。但是,当我删除这两行时,$config['quality'] 属性不起作用。我该如何解决这个问题并保存压缩它的图像的实际大小?

这是我的代码:

 $image_datar = $this->upload->data();  
 $config['image_library'] = 'gd2';  
 $config['source_image'] = './assets/img/single_courses/'.$image_datar["file_name"];  
 $config['maintain_ratio'] = false;
 $config['quality'] = '60%';
 $config['width'] = '750';
 $config['height'] = '500';
 $config['new_image'] = './assets/img/single_courses/'.$image_datar["file_name"];  
 $this->load->library('image_lib', $config);  
 $this->image_lib->resize();
 $post_image = $image_datar["file_name"];

【问题讨论】:

  • 嗯那么compressed是什么意思
  • @RiggsFolly 将 2MB 图像文件变成 500KB 图像文件
  • 您要调整大小的原始图像是否总是相同的大小?
  • @Vickel 我希望它们大小相同但质量较低
  • 好的,那么您需要获取源图像大小,我想您可以在 $image_datar 中找到它。尝试 print_r($image_datar);然后动态设置配置高度和宽度。如果不使用 php 函数 getimagesize(),请参见此处:php.net/manual/en/function.getimagesize.php

标签: php codeigniter


【解决方案1】:

即使在阅读了 cmets 以及您的代码指定宽度之后,您想要完成的工作也有点令人困惑。 如果您希望它是 750x500 并具有相同的比例(因此看起来不会“压缩”),那么您应该使用 $config['maintain_ratio'] = true; 生成:

如果您只是想降低图像的质量,以便 文件大小更小但保持与原始图像相同的尺寸,那么您可以注释掉原始图像的宽度和高度配置。但是,在我的测试中,即使将质量降低到 10%,也产生了与原始图像完全相同相同的文件大小。奇怪,虫子?我通过filesize() 和我的操作系统确认了这一点!

原来不是错误,而是编码功能:

// If the target width/height match the source, AND if the new file name is not equal to the old file name
// we'll simply make a copy of the original with the new name... assuming dynamic rendering is off.
if ($this->dynamic_output === FALSE && $this->orig_width === $this->width && $this->orig_height === $this->height)
{
    if ($this->source_image !== $this->new_image && @copy($this->full_src_path, $this->full_dst_path))
    {
        chmod($this->full_dst_path, $this->file_permissions);
    }

    return TRUE;
}

我试图想办法解决这个问题,但这需要覆盖和弄乱库功能。现在,如果您的图像宽度和高度比原始图像小 1px,您可以执行以下操作:

$source = $this->frontend_image_upload_path . 'org/upload_original.jpg';
list($width, $height) = getimagesize($source);
$config['image_library'] = 'gd2';
$config['source_image'] = $source;
//$config['maintain_ratio'] = true;
$config['quality'] = '20%';
$config['width'] = $width - 1;
$config['height'] = $height - 1;
$config['new_image'] = $this->frontend_image_upload_path . 'org/new_image.jpg';
$this->load->library('image_lib', $config);
if (!$this->image_lib->resize()) {
    echo $this->image_lib->display_errors();
}

【讨论】:

  • 我没有得到 1 件事。第一个代码,是什么意思?我应该将此代码包含在我的控制器中吗?还是只是例子?
  • 第一个代码是如果您真的想按照您在原始代码中指定的任何内容将尺寸更改为 700。第二个代码是如果你不这样做,只是想像你在 cmets 中所说的那样减小文件大小。
猜你喜欢
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
相关资源
最近更新 更多