본문 바로가기

Programing/PHP

PNG 용량을 줄이는 프로그램을 만들어 봅시다.




광고 플랫폼이나 기타등등을 만들다 보면 배너 용량에 대해서 신경을 쓸 수 밖에 없다.
그렇다고 해서 광고주에게 "PNG 타입을 용량을 줄여 주세요" 라고 하면 색상을 빼던지 단순화 시켜서 가져오며 불평을 늘어 놓게 된다.

그럼 어떻게 하면 좋을까를 찾아보다가 원래는 https://tinypng.com/ 을 이용하세요 하곤 한다.

그런데, 잘 구글링 해보면 분명 찾을 수 있을 것만 같아서 찾아보니...

두둥, 있다..

pngquant 라는 놈이 있었다.

압축하면 약 70% 정도 작아지고 투명배경도 지원한다.

어떻게 하면 될까 라는 생각에 무작정 해 보았다.

설치 방법은 너무도 심플했다.

서버를 KT 유클라우드로 이용하고 있고, CentOS5를 이용하고 있으니 yum을 이용하면된다. 그도 아니라면  RPM을 이용하면 되고, 것도 아니라면 소스 컴파일 하면 된다.

난, 게으름뱅이 이므로 yum을 이용한다.

server>yum install pngquant

이게 끝이다. 그러면 딱 설치가 된다.

이것은 command 방식이므로 PHP에 연동해야 해서 살짝 찾아보았더니, https://pngquant.org/php.html 메뉴얼이 뜬다.

일단 간단히 Function을 보면


/**
 * Optimizes PNG file with pngquant 1.8 or later (reduces file size of 24-bit/32-bit PNG images).
 *
 * You need to install pngquant 1.8 on the server (ancient version 1.0 won't work).
 * There's package for Debian/Ubuntu and RPM for other distributions on http://pngquant.org
 *
 * @param $path_to_png_file string - path to any PNG file, e.g. $_FILE['file']['tmp_name']
 * @param $max_quality int - conversion quality, useful values from 60 to 100 (smaller number = smaller file)
 * @return string - content of PNG file after conversion
 */
function compress_png($path_to_png_file, $max_quality = 90)
{
    if (!file_exists($path_to_png_file)) {
        throw new Exception("File does not exist: $path_to_png_file");
    }

    // guarantee that quality won't be worse than that.
    $min_quality = 60;

    // '-' makes it use stdout, required to save to $compressed_png_content variable
    // '<' makes it read from the given file path
    // escapeshellarg() makes this safe to use with any path
    $compressed_png_content = shell_exec("pngquant --quality=$min_quality-$max_quality - < ".escapeshellarg(    $path_to_png_file));

    if (!$compressed_png_content) {
        throw new Exception("Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?");
    }

    return $compressed_png_content;
}





그런데 보니 shell_exec를 이용한다. 보안상 안좋은데.... 라며 그냥 진행한다.


간단히 테스트 하기위해서 업로드 HTML과 해당 파일을 받는것을 해 보았다.


이 파일을 전송합니다:










잘된다....

쓸만한 놈을 구했다.

OPENJPEG도 써야 할텐데..... 그건 다음 기회에...