Sử dụng thư viện GD trong PHP để resize ảnh

Lưu ý: Đầu tiên bạn cần bật thư viện GD trong php.ini. Sau đó làm theo các bước sau

function img_resize($type,$from, $nx,$ny, $to)
    {
        $ext = $type;
        if ($ext == ‘jpg’ || $ext == ‘jpeg’)
        {
            $im = imagecreatefromjpeg($from);
        } else if ($ext == ‘gif’)
        {
            $im = imagecreatefromgif($from);
        }
        else if ($ext == ‘png’)
        {
            $im = imagecreatefrompng($from);
        }
        else
        {
            return false;
        }
        $sx = imagesx($im);
        $sy = imagesy($im);
       
        $nm = imagecreatetruecolor($nx, $ny);
        imagealphablending ($nm, false);
        imagecopyresampled ($nm, $im, 0, 0, 0, 0, $nx, $ny, $sx, $sy);
        if ($ext == ‘jpg’ || $ext == ‘jpeg’)
        {
            imagejpeg ($nm, $to);
        }
        else if ($ext == ‘gif’)
        {
            imagegif ($nm, $to);
        }
        else if ($ext == ‘png’)
        {
            imagesavealpha ($nm, true);
            imagepng ($nm, $to);
        }
        else
        {
            return false;
        }
    }

Ví dụ : img_resize(‘jpg’,'src.jpg’,100,100,’dst.jpg’);

Para1: Định dạng ảnh

Para2: Tệp nguồn

Para3 & 4: Kích cỡ đích (widthxheight)

Para 5: Tệp đích

Gửi phản hồi

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Thay đổi )

Twitter picture

You are commenting using your Twitter account. Log Out / Thay đổi )

Facebook photo

You are commenting using your Facebook account. Log Out / Thay đổi )

Connecting to %s

Follow

Get every new post delivered to your Inbox.