찾다
백엔드 개발PHP 튜토리얼ICO 아이콘을 생성하는 PHP 코드

이 글은 주로 PHP에서 ICO 아이콘을 생성하는 코드를 소개합니다. 관심 있는 친구들이 참고하면 도움이 될 것입니다.

투명 색상을 포함한 1개의 이미지 색상 교체

imagesavealpha($resize_im, true);//$resize_im 이미지의 투명한 색상을 잃지 마세요

전체 방법:

class phpthumb_ico {
 
  function phpthumb_ico() {
    return true;
  }
 
 
  function GD2ICOstring(&$gd_image_array) {
    foreach ($gd_image_array as $key => $gd_image) {
 
      $ImageWidths[$key] = ImageSX($gd_image);
      $ImageHeights[$key] = ImageSY($gd_image);
      $bpp[$key]     = ImageIsTrueColor($gd_image) ? 32 : 24;
      $totalcolors[$key] = ImageColorsTotal($gd_image);
 
      $icXOR[$key] = '';
      for ($y = $ImageHeights[$key] - 1; $y >= 0; $y--) {
        for ($x = 0; $x < $ImageWidths[$key]; $x++) {
          $argb = $this->GetPixelColor($gd_image, $x, $y);
          $a = round(255 * ((127 - $argb[&#39;alpha&#39;]) / 127));
          $r = $argb[&#39;red&#39;];
          $g = $argb[&#39;green&#39;];
          $b = $argb[&#39;blue&#39;];
 
          if ($bpp[$key] == 32) {
            $icXOR[$key] .= chr($b).chr($g).chr($r).chr($a);
          } elseif ($bpp[$key] == 24) {
            $icXOR[$key] .= chr($b).chr($g).chr($r);
          }
 
          if ($a < 128) {
            @$icANDmask[$key][$y] .= &#39;1&#39;;
          } else {
            @$icANDmask[$key][$y] .= &#39;0&#39;;
          }
        }
        // mask bits are 32-bit aligned per scanline
        while (strlen($icANDmask[$key][$y]) % 32) {
          $icANDmask[$key][$y] .= &#39;0&#39;;
        }
      }
      $icAND[$key] = &#39;&#39;;
      foreach ($icANDmask[$key] as $y => $scanlinemaskbits) {
        for ($i = 0; $i < strlen($scanlinemaskbits); $i += 8) {
          $icAND[$key] .= chr(bindec(str_pad(substr($scanlinemaskbits, $i, 8), 8, &#39;0&#39;, STR_PAD_LEFT)));
        }
      }
 
    }
 
    foreach ($gd_image_array as $key => $gd_image) {
      $biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);
 
      // BITMAPINFOHEADER - 40 bytes
      $BitmapInfoHeader[$key] = &#39;&#39;;
      $BitmapInfoHeader[$key] .= "\x28\x00\x00\x00";               // DWORD biSize;
      $BitmapInfoHeader[$key] .= $this->LittleEndian2String($ImageWidths[$key], 4);   // LONG  biWidth;
      // The biHeight member specifies the combined
      // height of the XOR and AND masks.
      $BitmapInfoHeader[$key] .= $this->LittleEndian2String($ImageHeights[$key] * 2, 4); // LONG  biHeight;
      $BitmapInfoHeader[$key] .= "\x01\x00";                   // WORD  biPlanes;
        $BitmapInfoHeader[$key] .= chr($bpp[$key])."\x00";             // wBitCount;
      $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";               // DWORD biCompression;
      $BitmapInfoHeader[$key] .= $this->LittleEndian2String($biSizeImage, 4);      // DWORD biSizeImage;
      $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";               // LONG  biXPelsPerMeter;
      $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";               // LONG  biYPelsPerMeter;
      $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";               // DWORD biClrUsed;
      $BitmapInfoHeader[$key] .= "\x00\x00\x00\x00";               // DWORD biClrImportant;
    }
 
 
    $icondata = "\x00\x00";                   // idReserved;  // Reserved (must be 0)
    $icondata .= "\x01\x00";                   // idType;    // Resource Type (1 for icons)
    $icondata .= $this->LittleEndian2String(count($gd_image_array), 2); // idCount;   // How many images?
 
    $dwImageOffset = 6 + (count($gd_image_array) * 16);
    foreach ($gd_image_array as $key => $gd_image) {
      // ICONDIRENTRY  idEntries[1]; // An entry for each image (idCount of &#39;em)
 
      $icondata .= chr($ImageWidths[$key]);           // bWidth;     // Width, in pixels, of the image
      $icondata .= chr($ImageHeights[$key]);          // bHeight;     // Height, in pixels, of the image
      $icondata .= chr($totalcolors[$key]);           // bColorCount;   // Number of colors in image (0 if >=8bpp)
      $icondata .= "\x00";                   // bReserved;    // Reserved ( must be 0)
 
      $icondata .= "\x01\x00";                 // wPlanes;     // Color Planes
      $icondata .= chr($bpp[$key])."\x00";           // wBitCount;    // Bits per pixel
 
      $dwBytesInRes = 40 + strlen($icXOR[$key]) + strlen($icAND[$key]);
      $icondata .= $this->LittleEndian2String($dwBytesInRes, 4);    // dwBytesInRes;  // How many bytes in this resource?
 
      $icondata .= $this->LittleEndian2String($dwImageOffset, 4);   // dwImageOffset;  // Where in the file is this image?
      $dwImageOffset += strlen($BitmapInfoHeader[$key]);
      $dwImageOffset += strlen($icXOR[$key]);
      $dwImageOffset += strlen($icAND[$key]);
    }
 
    foreach ($gd_image_array as $key => $gd_image) {
      $icondata .= $BitmapInfoHeader[$key];
      $icondata .= $icXOR[$key];
      $icondata .= $icAND[$key];
    }
 
    return $icondata;
  }
 
  function LittleEndian2String($number, $minbytes=1) {
    $intstring = &#39;&#39;;
    while ($number > 0) {
      $intstring = $intstring.chr($number & 255);
      $number >>= 8;
    }
    return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
  }
 
  function GetPixelColor(&$img, $x, $y) {
    if (!is_resource($img)) {
      return false;
    }
    return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
  }
 
}

3, 프론트 데스크

Yii::$enableIncludePath = false;
Yii::import ( &#39;application.extensions.ico.phpthumb_ico&#39;, 1 );

공유하겠습니다 당신은 독립적인 수업입니다

phpthumb.ico.php

/**
   * icoMaker 在线生成ICO图标
   * @author flashalliance
   */
  public function actionIco() {
    $this->breadcrumbs=array_merge($this->breadcrumbs,array(
        &#39;ICO图标制作&#39;
    ));
    $output = "";
    $errors=array();
    if(isset($_GET[&#39;action&#39;])&&$_GET[&#39;action&#39;] == &#39;make&#39;){
      if(isset($_FILES[&#39;upimage&#39;][&#39;tmp_name&#39;]) && $_FILES[&#39;upimage&#39;][&#39;tmp_name&#39;] && is_uploaded_file($_FILES[&#39;upimage&#39;][&#39;tmp_name&#39;])){
        if($_FILES[&#39;upimage&#39;][&#39;size&#39;]>204800){
          $errors[]="你上传的文件过大,最大不能超过200K。";
        }
        $fileext = array("image/pjpeg","image/jpeg","image/gif","image/x-png","image/png");
        if(!in_array($_FILES[&#39;upimage&#39;][&#39;type&#39;],$fileext)){
          $errors[]="你上传的文件格式不正确,仅支持 png, jpg, gif格式。";
        }
        if($im = @imagecreatefrompng($_FILES[&#39;upimage&#39;][&#39;tmp_name&#39;]) or $im = @imagecreatefromgif($_FILES[&#39;upimage&#39;][&#39;tmp_name&#39;]) or $im = @imagecreatefromjpeg($_FILES[&#39;upimage&#39;][&#39;tmp_name&#39;])){
          $imginfo = @getimagesize($_FILES[&#39;upimage&#39;][&#39;tmp_name&#39;]);
          if(!is_array($imginfo)){
            $errors[]="图像格式错误!";
          }
          if(empty($errors)){
            switch($_POST[&#39;size&#39;]){
              case 1;
              $resize_im = @imagecreatetruecolor(16,16);
              $size = 16;
              break;
              case 2;
              $resize_im = @imagecreatetruecolor(32,32);
              $size = 32;
              break;
              case 3;
              $resize_im = @imagecreatetruecolor(48,48);
              $size = 48;
              break;
              default;
              $resize_im = @imagecreatetruecolor(32,32);
              $size = 32;
              break;
            }
 
            imagesavealpha($im, true);
            imagealphablending($resize_im, false);//不合并颜色,直接用$im图像颜色替换,包括透明色
            imagesavealpha($resize_im, true);//不要丢了$resize_im图像的透明色,解决生成黑色背景的问题
            imagecopyresampled($resize_im,$im,0,0,0,0,$size,$size,$imginfo[0],$imginfo[1]);
 
            Yii::$enableIncludePath = false;
            Yii::import ( &#39;application.extensions.ico.phpthumb_ico&#39;, 1 );
            $icon = new phpthumb_ico();
            $gd_image_array = array($resize_im);
            $icon_data = $icon->GD2ICOstring($gd_image_array);
            $bas_path=dirname ( Yii::app ()->BasePath );
            $bas_new_path=$bas_path.&#39;/upload/ico/&#39;;
            if(!is_dir($bas_new_path)){
              mkdir($bas_new_path, 0777, true);
            }
            $filePath=$bas_new_path. date("Ymdhis").uniqid(). rand(1,1000) . ".ico";
            if(file_put_contents($filePath, $icon_data)){
              $output = str_replace($bas_path,&#39;&#39;,$filePath);
            }
          }
        }else{
          $errors[]="生成错误请重试!";
        }
      }
    }
    $this->render ( &#39;ico&#39;,array(&#39;output&#39;=>$output,&#39;errors&#39;=>$errors));
  }

index.php
<p class="col-md-12">
  <p class="form-horizontal panel panel-default margin-t-10 b-img">
    <p class="panel-heading">
      <p class="pull-left"><span class="g-bg glyphicon glyphicon-wrench margin-r-2" aria-hidden="true"></span>在线制作ICO图标</p>
      <p class="clearfix"></p>
    </p>
<?php
$form = $this->beginWidget ( &#39;CActiveForm&#39;, array (
    &#39;id&#39; => &#39;ico-form&#39;,
    &#39;htmlOptions&#39; => array (
        &#39;id&#39; => &#39;view_table&#39;,
        &#39;class&#39; => &#39;add-form padding-10&#39;,
        &#39;enctype&#39;=>&#39;multipart/form-data&#39;
    ),
    &#39;action&#39;=>&#39;/tool/ico?action=make&#39;,
    &#39;enableAjaxValidation&#39; => false
) );
?>
    <p class="form-group">
        <label class="col-lg-2 control-label">上传文件</label>
        <p class="col-md-5">
          <p class="col-md-6">
            <input id="upimage" type="file" name="upimage" class="hidden">
            <input id="tmp_file" class="form-control" type="text">
          </p>
          <p class="col-md-6"><a class="btn btn-default" onclick="$(&#39;input[id=upimage]&#39;).click();">选择文件</a></p>
        </p>
    </p>
    <p class="form-group">
        <label class="col-lg-2 text-right">选择尺寸</label>
        <p class="col-lg-5 btn-group" data-toggle="buttons">
            <label class="btn btn-sm btn-default">
             <input type="radio" name="size" id="s1" value="1" checked="checked"> 16*16
            </label>
            <label class="btn btn-sm btn-default">
             <input type="radio" name="size" id="s2" value="2"> 32*32
            </label>
            <label class="btn btn-sm btn-default">
             <input type="radio" name="size" id="s3" value="3"> 48*48
            </label>
        </p>
    </p>
    <p class="form-group">
      <label class="col-lg-2 text-right">支持格式</label>
      <p class="col-lg-5">
       png,jpg,gif
      </p>
    </p>
    <p class="list_back">
      <input type="submit" value="生 成" class="btn btn-success">
    </p>
  </p>
<?php $this->endWidget(); ?>
<?php if(!empty($errors) or !empty($output)):?>
  <p class="form-horizontal panel panel-default margin-t-10 b-img">
    <p class="panel-heading margin-b-10">
      <p class="pull-left"><span class="g-bg glyphicon glyphicon-wrench margin-r-2" aria-hidden="true"></span>生成结果</p>
      <p class="clearfix"></p>
    </p>
    <?php if(!empty($errors)):?>
    <p class="form-group">
      <label class="col-lg-2 text-right">生成失败</label>
      <p class="col-lg-5">
      <?php foreach ($errors as $e):?>
      <?php echo $e;?><br>
      <?php endforeach;?>
      </p>
    </p>
    <?php endif;?>
    <?PHP if (!empty($output)):?>
    <?php
    $form = $this->beginWidget ( &#39;CActiveForm&#39;, array (
        &#39;id&#39; => &#39;ico-form&#39;,
        &#39;htmlOptions&#39; => array (
            &#39;id&#39; => &#39;view_table&#39;,
            &#39;class&#39; => &#39;add-form padding-10&#39;,
        ),
        &#39;action&#39;=>&#39;/tool/icoDownload&#39;,
        &#39;enableAjaxValidation&#39; => false
    ) );
    ?>
    <?php echo CHtml::hiddenField(&#39;filePath&#39;,$output);?>
    <p class="form-group">
      <label class="col-lg-2 text-right">成功生成</label>
      <p class="col-lg-5">
        <img  src="/static/imghwm/default1.png"  data-src="<?php echo $output;? alt="ICO 아이콘을 생성하는 PHP 코드" >"  class="lazy"  alt="在线制作ICO图标_favicon.ico"  class="margin-r-10">
        <input type="submit" value="立即下载" class="btn btn-sm btn-success margin-l-10">
      </p>
    </p>
    <?php $this->endWidget(); ?>
    <?php endif;?>
  </p>
<?php endif;?>
</p>
<!-- form -->

요약: 위 내용은 이 글의 전체 내용입니다. 모든 사람의 학습에 도움이 되기를 바랍니다.

관련 권장사항:

PHP 관찰자 모드에 대한 자세한 설명

PHP가 메일 클래스를 기반으로 이메일을 보내는 방법

PHP 제출 게시물 배열 매개변수 사용

위 내용은 ICO 아이콘을 생성하는 PHP 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄)11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄)Mar 03, 2025 am 10:49 AM

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram API 소개Instagram API 소개Mar 02, 2025 am 09:32 AM

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel의 플래시 세션 데이터로 작업합니다Laravel의 플래시 세션 데이터로 작업합니다Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

Laravel Back End : Part 2, React가있는 React 앱 구축Laravel Back End : Part 2, React가있는 React 앱 구축Mar 04, 2025 am 09:33 AM

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel 테스트에서 단순화 된 HTTP 응답 조롱Laravel 테스트에서 단순화 된 HTTP 응답 조롱Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP 상황 조사 발표2025 PHP 상황 조사 발표Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다

See all articles

핫 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.