APSB
APSB

Reputation: 587

Reduce image quality in php

How can I reduce the quality of an image using PHP ?

upload_mode = @$this->setting->upload_mode?:'file';
            $upload_path = @$this->setting->upload_path?:'uploads/';

            $file               = Request::file($name);
            $fm                 = array();
            $fm['name']         = $_FILES[$name]['name'];                   
            $fm['ext']          = $file->getClientOriginalExtension();
            $fm['size']         = $_FILES[$name]['size'];
            $fm['content_type'] = $_FILES[$name]['type'];

            if($upload_mode=='database') {
                $fm['filedata']     = file_get_contents($_FILES[$name]['tmp_name']);
                DB::table('cms_filemanager')->insert($fm);
                $id_fm              = DB::getPdo()->lastInsertId();
                DB::table('cms_filemanager')->where('id',$id_fm)->update(['id_md5' =>md5($id_fm)]);
                $filename           = 'upload_virtual/files/'.md5($id_fm).'.'.$fm['ext'];
            }else{
                if(!file_exists($upload_path.date('Y-m'))) {
                    if(!mkdir($upload_path.date('Y-m'),0777)) {
                        die('Gagal buat folder '.$upload_path.date('Y-m'));
                    }
                }
                $filename = md5(str_random(12)).'.'.$fm['ext'];
                $file->move($upload_path.date('Y-m'),$filename);                        
                $filename = $upload_path.date('Y-m').'/'.$filename;
            }

            $url                = asset($filename);

have someone help me ? what i need add to make it work like what i need ?

Upvotes: 0

Views: 2124

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

GD is an open source code library for the dynamic creation of images by programmers. GD is written in C, and "wrappers" are available for Perl, PHP and other languages. GD creates PNG, JPEG and GIF images, among other formats. GD is commonly used to generate charts, graphics, thumbnails, and most anything else, on the fly.

Code to reduce file size for the image:

<?php 
    function compress($source, $destination, $quality) {

        $info = getimagesize($source);

        if ($info['mime'] == 'image/jpeg') 
            $image = imagecreatefromjpeg($source);

        elseif ($info['mime'] == 'image/gif') 
            $image = imagecreatefromgif($source);

        elseif ($info['mime'] == 'image/png') 
            $image = imagecreatefrompng($source);

        imagejpeg($image, $destination, $quality);

        return $destination;
    }

    $source_img = 'source.jpg';
    $destination_img = 'destination .jpg';

    $d = compress($source_img, $destination_img, 90);
 ?>
$d = compress($source_img, $destination_img, 90);

Reference

Upvotes: 3

Related Questions