백엔드 개발 PHP 튜토리얼 PHP를 사용하여 다양한 크기의 로고를 일괄 생성하는 방법

PHP를 사용하여 다양한 크기의 로고를 일괄 생성하는 방법

Jun 12, 2018 pm 01:56 PM
app logo php 생성하다

이 글은 주로 PHP에서 다양한 크기의 로고를 일괄 생성하는 방법의 핵심 코드를 소개합니다. 필요하면 여기에서 참고할 수 있습니다.

사용하기 쉬운 PHP GD를 사용하고 한 번의 클릭으로 다양한 크기를 잘라서 패키지하고 다운로드할 수 있습니다. 아이콘을 자주 바꾸는 분들은 아실텐데, 아티스트가 1024 로고를 주고, 다양한 크기로 포토샵을 해야 해서 이런 걸 생각해냈습니다.

코드는 다음과 같습니다.

<?php
class image {
    /**
     * source image
     *
     * @var string|array
     */
    private $source;
    /**
     * temporay image
     *
     * @var file
     */
    private $image;
    private $ext;
    /**
     * erros
     *
     * @var array
     */
    private $error;
    /**
     * construct
     *
     * @param string|array $source
     */
    public function __construct($source = NULL) {
        if($source != NULL) {
            $this->source($source);
        }
    }
    /**
     * set the source image
     *
     * @param string|array $source
     */
    public function source($source) { 
        if(!is_array($source)) {
            $this->source["name"] = $source;
            $this->source["tmp_name"] = $source;
            $type = NULL;
            $ext = strtolower(end(explode(".",$source)));
            switch($ext) {
                case "jpg"  : 
                case "jpeg" : $type = "image/jpeg"; break;
                case "gif"  : $type = "image/gif"; break;
                case "png"  : $type = "image/png"; break;
            }
            $this->source["type"] = $type;
        } else {
            $this->source = $source;
        }
        $this->destination = $this->source["name"];
    }
    /**
     * resize the image
     *
     * @param int $width
     * @param int $height
     */
    public function resize($width = NULL,$height = NULL) {
        if(isset($this->source["tmp_name"]) && file_exists($this->source["tmp_name"])) {
            list($source_width,$source_height) = getimagesize($this->source["tmp_name"]);
            if(($width == NULL) && ($height != NULL)) {
                $width = ($source_width * $height) / $source_height;
            }
            if(($width != NULL) && ($height == NULL)) {
                $height = ($source_height * $width) / $source_width;
            }
            if(($width == NULL) && ($height == NULL)) {
                $width = $source_width;
                $height = $source_height;
            }
            switch($this->source["type"]) {
                case "image/jpeg" : $created = imagecreatefromjpeg($this->source["tmp_name"]); break;
                case "image/gif"  : $created = imagecreatefromgif($this->source["tmp_name"]);  break;
                case "image/png"  : $created = imagecreatefrompng($this->source["tmp_name"]);  break;
            }
            $this->image = imagecreatetruecolor($width,$height);
            imagecopyresampled($this->image,$created,0,0,0,0,$width,$height,$source_width,$source_height);
        }
    }
    /**
     * add watermark on image
     *
     * @param string $mark
     * @param int $opac
     * @param int $x_pos
     * @param int $y_pos
     */
    public function watermark($mark,$opac,$x_pos,$y_pos) {
        if(file_exists($mark) && ($this->image != "")) {
            $ext = strtolower(end(explode(".",$mark)));
            switch($ext) {
                case "jpg"  : 
                case "jpeg" : $watermark = imagecreatefromjpeg($mark); break;
                case "gif"  : $watermark = imagecreatefromgif($mark);  break;
                case "png"  : $watermark = imagecreatefrompng($mark);  break;
            }
            list($watermark_width,$watermark_height) = getimagesize($mark);
            $source_width = imagesx($this->image);
            $source_height = imagesy($this->image);
            if($x_pos == "top") $pos  = "t"; else $pos  = "b";
            if($y_pos == "left") $pos .= "l"; else $pos .= "r";
            $dest_x = 0; 
            $dest_y = 0; 
            switch($pos) {
                case "tr" : $dest_x = $source_width - $watermark_width; break;
                case "bl" : $dest_y = $source_height - $watermark_height; break;
                case "br" : $dest_x = $source_width - $watermark_width; $dest_y = $source_height - $watermark_height; break;
            }
            imagecopymerge($this->image,$watermark,$dest_x,$dest_y,0,0,$watermark_width,$watermark_height,$opac);
        }
    }
    /**
     * crop the image
     *
     * @param int $x
     * @param int $y
     * @param int $width
     * @param int $height
     */
    public function crop($x,$y,$width,$height) {
        if(isset($this->source["tmp_name"]) && file_exists($this->source["tmp_name"]) && ($width > 10) && ($height > 10)) {
            switch($this->source["type"]) {
                case "image/jpeg" : $created = imagecreatefromjpeg($this->source["tmp_name"]); break;
                case "image/gif"  : $created = imagecreatefromgif($this->source["tmp_name"]);  break;
                case "image/png"  : $created = imagecreatefrompng($this->source["tmp_name"]);  break;
            }           
            $this->image = imagecreatetruecolor($width,$height);
            imagecopy($this->image,$created,0,0,$x,$y,$width,$height);
        }
    }
    /**
     * create final image file 
     *
     * @param string $destination
     * @param int $quality
     */
    public function create($destination,$quality = 100) {
        if($this->image != "") {
            $extension = substr($destination,-3,3);
            switch($extension) {
                case "gif" :  
                    imagegif($this->image,$destination,$quality); 
                    break;
                case "png" :
                    $quality = ceil($quality/10) - 1;
                    imagepng($this->image,$destination,$quality); 
                    break;
                default    : 
                    imagejpeg($this->image,$destination,$quality); 
                    break;
            }
        }
    }
    /**
     * check if extension is valid
     *
     */
    public function validate_extension() {
        if(isset($this->source["tmp_name"]) && file_exists($this->source["tmp_name"])) {
            $exts = array("image/jpeg", "image/pjpeg", "image/png", "image/x-png");
            $ext = $this->source["type"];
            $valid = 0;
            $this->ext = &#39;.not_found&#39;;
            if ($ext == $exts[0] || $ext == $exts[1]) {
                $valid = 1;
                $this->ext = &#39;.jpg&#39;;
            }
            // if ($ext == $exts[2]) {
            //  $valid = 1;
            //  $this->ext = &#39;.gif&#39;;
            // }
            if ($ext == $exts[2] || $ext == $exts[3]) {
                $valid = 1;
                $this->ext = &#39;.png&#39;;
            }
            if($valid != 1) {
                $this->error .= "extension";
            }
        } else {
            $this->error .= "source";
        }
    }
    /**
     * check if the size is correct
     *
     * @param int $max
     */
    public function validate_size($max) {
        if(isset($this->source["tmp_name"]) && file_exists($this->source["tmp_name"])) {
            $max = $max * 1024;
            if($this->source["size"] >= $max) {
                $this->error .= "size";
            }
        } else {
            $this->error .= "source";
        }
    }
    /**
     * check if the dimension is correct
     *
     * @param int $limit_width
     * @param int $limit_height
     */
    public function validate_dimension($limit_width,$limit_height) {
        if(isset($this->source["tmp_name"]) && file_exists($this->source["tmp_name"])) {
            list($source_width,$source_height) = getimagesize($this->source["tmp_name"]);
            if(($source_width > $limit_width) || ($source_height > $limit_height)) {
                $this->error .= "dimension";
            }
        } else {
            $this->error .= "source";
        }
    }
    /**
     * get the found errors
     *
     */
    public function error() {
        $error = array();
        if(stristr($this->error,"source")) $error[] = "找不到上传文件";
        if(stristr($this->error,"dimension")) $error[] = "上传图片尺寸太大";
        if(stristr($this->error,"extension")) $error[] = "不符合要求的格式";
        if(stristr($this->error,"size")) $error[] = "图片文件太大";
        return $error;
    }
    public function error_string() {
        $error = "";
        if(stristr($this->error,"source")) $error .= "找不到上传文件 / ";
        if(stristr($this->error,"dimension")) $error .= "上传图片尺寸太大 / ";
        if(stristr($this->error,"extension")) $error .= "不符合要求的格式 / ";
        if(stristr($this->error,"size")) $error .= "图片文件太大 / ";
        if(eregi(" / $", $error)) {
            $error = substr($error, 0, -3);
        }
        return $error;
    }
    public function ext() {
        return $this->ext;
    }
}
로그인 후 복사

요약: 위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되길 바랍니다.

관련 권장 사항:

PHP는 Ajax를 기반으로 새로 고침이 없는 로그인 및 종료를 구현합니다.

php는 색상 값을 작동하여 색상을 역 색상으로 변환합니다.

php는 정규 표현식을 통해 구문 강조를 구현합니다.

위 내용은 PHP를 사용하여 다양한 크기의 로고를 일괄 생성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP의 지속적인 사용 : 지구력의 이유 PHP의 지속적인 사용 : 지구력의 이유 Apr 19, 2025 am 12:23 AM

여전히 인기있는 것은 사용 편의성, 유연성 및 강력한 생태계입니다. 1) 사용 편의성과 간단한 구문은 초보자에게 첫 번째 선택입니다. 2) 웹 개발, HTTP 요청 및 데이터베이스와의 우수한 상호 작용과 밀접하게 통합되었습니다. 3) 거대한 생태계는 풍부한 도구와 라이브러리를 제공합니다. 4) 활성 커뮤니티와 오픈 소스 자연은 새로운 요구와 기술 동향에 맞게 조정됩니다.

session_start ()가 여러 번 호출되면 어떻게됩니까? session_start ()가 여러 번 호출되면 어떻게됩니까? Apr 25, 2025 am 12:06 AM

Session_Start ()로 여러 통화를하면 경고 메시지와 가능한 데이터 덮어 쓰기가 발생합니다. 1) PHP는 세션이 시작되었다는 경고를 발행합니다. 2) 세션 데이터의 예상치 못한 덮어 쓰기를 유발할 수 있습니다. 3) Session_status ()를 사용하여 반복 통화를 피하기 위해 세션 상태를 확인하십시오.

IIS 및 PHP의 호환성 : 깊은 다이빙 IIS 및 PHP의 호환성 : 깊은 다이빙 Apr 22, 2025 am 12:01 AM

IIS 및 PHP는 호환 가능하며 FastCGI를 통해 구현됩니다. 1. IIS 구성 파일을 통해 .php 파일 요청을 FastCGI 모듈로 전달합니다. 2. FASTCGI 모듈은 PHP 프로세스를 시작하여 요청을 처리하여 성능과 안정성을 향상시킵니다. 3. 실제 응용 프로그램에서는 구성 세부 사항, 오류 디버깅 및 성능 최적화에주의를 기울여야합니다.

session_start () 함수의 중요성은 무엇입니까? session_start () 함수의 중요성은 무엇입니까? May 03, 2025 am 12:18 AM

session_start () iscrucialinphpformanagingUsersessions.1) itiniteSanewsessionifnoneexists, 2) ResumesAnxistessions, and3) setSasessionCookieForContInuityAcrosrequests, enablingplicationsirecationSerauthenticationAndpersonalizestContent.

작곡가 : AI를 통한 PHP 개발 지원 작곡가 : AI를 통한 PHP 개발 지원 Apr 29, 2025 am 12:27 AM

AI는 작곡가 사용을 최적화하는 데 도움이 될 수 있습니다. 특정 방법에는 다음이 포함됩니다. 1. 종속성 관리 최적화 : AI는 종속성을 분석하고 최상의 버전 조합을 권장하며 충돌을 줄입니다. 2. 자동화 된 코드 생성 : AI는 모범 사례를 준수하는 composer.json 파일을 생성합니다. 3. 코드 품질 향상 : AI는 잠재적 인 문제를 감지하고 최적화 제안을 제공하며 코드 품질을 향상시킵니다. 이러한 방법은 기계 학습 및 자연어 처리 기술을 통해 구현되어 개발자가 효율성과 코드 품질을 향상시킬 수 있도록 도와줍니다.

Laravel 사용 : PHP로 웹 개발을 간소화합니다 Laravel 사용 : PHP로 웹 개발을 간소화합니다 Apr 19, 2025 am 12:18 AM

Laravel은 다음을 포함하여 웹 개발 프로세스를 최적화합니다. 1. 라우팅 시스템을 사용하여 URL 구조를 관리합니다. 2. 블레이드 템플릿 엔진을 사용하여보기 개발을 단순화하십시오. 3. 대기열을 통해 시간이 많이 걸리는 작업을 처리합니다. 4. eloquentorm을 사용하여 데이터베이스 작업을 단순화하십시오. 5. 모범 사례를 따라 코드 품질과 유지 관리를 향상시킵니다.

PHP 및 IIS : 함께 일하게합니다 PHP 및 IIS : 함께 일하게합니다 Apr 21, 2025 am 12:06 AM

IIS에서 PHP 구성 및 실행에는 다음 단계가 필요합니다. 1) PHP 다운로드 및 설치, 2) IIS 구성 및 FASTCGI 모듈 추가, 3) 응용 프로그램 풀 생성 및 설정 4) 웹 사이트를 만들고 응용 프로그램 풀에 바인딩합니다. 이러한 단계를 통해 스케일링을 구성하고 성능을 최적화하여 Windows 서버에 PHP 응용 프로그램을 쉽게 배포하고 응용 프로그램 안정성 및 효율성을 향상시킬 수 있습니다.

데이터 처리 및 계산에 MySQL 기능을 사용하는 방법 데이터 처리 및 계산에 MySQL 기능을 사용하는 방법 Apr 29, 2025 pm 04:21 PM

MySQL 기능은 데이터 처리 및 계산에 사용될 수 있습니다. 1. 기본 사용에는 문자열 처리, 날짜 계산 및 수학 연산이 포함됩니다. 2. 고급 사용에는 복잡한 작업을 구현하기 위해 여러 기능을 결합하는 것이 포함됩니다. 3. 성능 최적화를 위해서는 WHERE 절에서 기능 사용 및 GroupBy 및 임시 테이블 사용을 피해야합니다.

See all articles