[Laravel] GD라이브러리 이미지 사이즈 조절하기

florentyoon·2021년 6월 1일
0

Laravel

목록 보기
4/12

1. 라라벨에선 GD 라이브러리를 제공한다.

기본적으로 라라벨에서 이미지를 수정할 수 있도록 제공한다.
만약 활성화 되지 않았다면 composer.json에서

    "require": {

        "ext-gd": "*",

추가해준다.

아래 코드는 사이즈를 조절하는 함수를 만들었다.
filepath와 $localpath는 이미지의 위치. filepath는 aws s3에 저장되있는 원본 파일 위치이고, $localpath는 저장될 위치이다. (이때 $localpath에 파일명까지 붙어있어야 마지막에 그 이름으로 저장된다.)

// image size 수정
    public function setImageSize($filepath, $localpath){
        // 파일 사이즈 가져오기
        $ext = getimagesize($filepath);
        $orginWidth = $ext[0];
        $orginHeight = $ext[1];

        // 수정 비율
        if($orginWidth > 1950 || $orginHeight > 1950){
            $s = 0.7;
        }else if($orginWidth > 1200 || $orginHeight > 1200){
            $s = 0.89;
        }else{
            $s = 1;
        }

        // 수정 가로
        $newWidth = $orginWidth * $s;
        // 수정 세로
        $newHeight = $orginHeight * $s;

        switch ($ext['mime']){
            case 'image/jpeg' : $image = imagecreatefromjpeg($filepath);
                break;
            case 'image/png' :  $image = imagecreatefrompng($filepath);
                break;
        }
        // resize 대상 image 생성
        $reImage= imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($reImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $orginWidth, $orginHeight);
        imagejpeg($reImage, $localpath);

2. 원리

간단히 생각하면, 원본이미지를 줄여서 이미지를 만드는게 아닌, 원하는 크기로 조절한 빈이미지를 생성해서 거기에 원본이미지를 담는 것이라 볼수 있다.
그래서인지 화질 저하는 어느정도 발생한다. imagecopyresized는 imagecopyresampled보다 품질이 더 떨어지므로 왠만해선 쓰지 않는다.

결국 새로 생성한 사이즈의 이미지에 새로 생성한 컬러값을 담은 새 이미지를 imagejpeg함수를 통해 저장하는 것이다.
이러면 아까 지정한 $localpath에 의해 이미지가 저장된다.

profile
florentyoon의 IT 세상

0개의 댓글