Image compress in Codeigniter3

后端 未结 1 877
半阙折子戏
半阙折子戏 2021-01-25 18:36

I have a piece of code where I compress images via Codeigniter gd2 library. However, it turns this photo

into this one

because I set width and

相关标签:
1条回答
  • 2021-01-25 18:58

    It's a bit confusing what you are trying to accomplish even after reading the comments, and your code as it specifies the width. If you want it to be 750x500 by have the same ratio (so things don't look "compressed") than you should have $config['maintain_ratio'] = true; which generates:

    If you just want to reduce the quality of the image so that the file size is smaller yet keep the same dimensions of the original image than one would think you can comment out the width and height of the config. However, in my testing that yielded the exact same file size as the original image, even when changing the quality down to 10%. Weird, bug? I confirmed this with filesize() and in my os!

    Turns out not a bug, but a coded feature:

    // 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;
    }
    

    I've tried to figure out a way to get around this but that would require overwriting and messing with the libraries functionality. For now, and if your ok with your image being 1px less in width and height than the original, you can do something like:

    $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();
    }
    
    0 讨论(0)
提交回复
热议问题