PHP code example of forgetphp / image-compression

1. Go to this page and download the library: Download forgetphp/image-compression library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

forgetphp / image-compression example snippets



use Image\Compression\Type;
use Image\Contract\FinishInterface;
use Image\Contract\ReportEncodingProgressInterface;
use Image\Event\Finish;
use Image\Event\ReportEncodingProgress;
use Image\ImageFactory;
use Image\Listener\FinishListener;
use Image\Listener\ReportEncodingProgressListener;

//监听压缩进度事件(如果需要)
class ReportListener extends ReportEncodingProgressListener
{

    /**
     * @param ReportEncodingProgress| object $event
     */
    public function process( object $event )
    {
        //压缩进度
        //$event->progress; 
        //当前文件名
        //$event->currentFile;
       
    }
}

//监听压缩完成事件(如果需要)
class CompressionFinishListener extends FinishListener
{
    /**
     * @param Finish| object $event
     */
    public function process( object $event )
    {
        $event->currentFile;//当前文件名
        $event->compressionRatio;//压缩比
        $event->distImageSize;//压缩后文件大小
        $event->distPath;//压缩后文件路径
        $event->originImageSize;//原图大小
    }
}

$config = [
    'type'       => Type::CJPEG , //压缩类型
    'output_dir' => './runtime', //文件输出路径
    //'bin' => '',//对应bin的路径。默认不用填写。如果在本地无法正常运行。请编译对应平台的可执行文件后配置该项

    'listener'   => [
        //ReportEncodingProgressInterface::class => ReportListener::class , //压缩进度事件
        //FinishInterface::class                 => CompressionFinishListener::class ,//压缩完成事件
    ] ,
];

$image = ImageFactory::create($config);

$image->setQuality(75);

$image->enableAsync();

$image->input('demo.jpg');

$image->inputs([
   'https://wenda.swoole.com/storage/avatar/avatar-1.png',
   'WechatIMG409.jpeg'
]);

//or

$image->inputs([
   [ 'WechatIMG409.jpeg' , 'outfilename'],
   ['https://wenda.swoole.com/storage/avatar/avatar-1.png','输出文件名。不需要带后缀。可不传同 input()' ],
]);

$image->->crop(100,100,100,100);

$image->->resize(10,10);

$result = $image->->output();

$result = ImageFactory::create($config)
    ->input( 'demo.jpg' )
    ->output( );