讲师中心 微信公众号

工具推荐

视频效率加速
Seko
Seko

AI短剧一键生成成片

SoundView
SoundView

字幕擦除翻译、配音口型同步

立刻MV
立刻MV

低成本歌曲 MV、视频生成

AniShort
AniShort

AI短剧协同制作平台

PHP生成ICO图标使用phpthumb_ico类完整实例

小磊酱_2118

小磊酱_2118

发布时间:2017-03-30 13:36:26

|

2882人浏览过

|

来源于php中文网

原创

这里我使用的是yii框架。

1,phpthumb_ico 是生成ICO图标的类,源码如下

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['alpha']) / 127));
                    $r = $argb['red'];
                    $g = $argb['green'];
                    $b = $argb['blue'];

                    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] .= '1';
                    } else {
                        @$icANDmask[$key][$y] .= '0';
                    }
                }
                // mask bits are 32-bit aligned per scanline
                while (strlen($icANDmask[$key][$y]) % 32) {
                    $icANDmask[$key][$y] .= '0';
                }
            }
            $icAND[$key] = '';
            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, '0', STR_PAD_LEFT)));
                }
            }

        }

        foreach ($gd_image_array as $key => $gd_image) {
            $biSizeImage = $ImageWidths[$key] * $ImageHeights[$key] * ($bpp[$key] / 8);

            // BITMAPINFOHEADER - 40 bytes
 $BitmapInfoHeader[$key]  = '';
 $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);// LONGbiHeight;
   $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 '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 = '';
        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));
    }

}

2,后台

引入类:

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

解决生成黑色背景的问题

立即学习“PHP免费学习笔记(深入)”;

Build MCP servers and clients for PHP applications with the official PHP SDK
Build MCP servers and clients for PHP applications with the official PHP SDK

使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

下载
imagealphablending($resize_im, false);//不合并颜色,直接用$im图像颜色替换,包括透明色
imagesavealpha($resize_im, true);//不要丢了$resize_im图像的透明色
完整方法:

完整方法:

/**
	 * icoMaker 在线生成ICO图标
	 * @author flashalliance
	 */
	public function actionIco() {
		$this->breadcrumbs=array_merge($this->breadcrumbs,array(
				'ICO图标制作'
		));
		$output = "";
		$errors=array();
		if(isset($_GET['action'])&&$_GET['action'] == 'make'){
if(isset($_FILES['upimage']['tmp_name']) && $_FILES['upimage']['tmp_name'] && 
is_uploaded_file($_FILES['upimage']['tmp_name'])){
				if($_FILES['upimage']['size']>204800){
					$errors[]="你上传的文件过大,最大不能超过200K。";
				}
$fileext = array("image/pjpeg","image/jpeg","image/gif","image/x-png","image/png");
				if(!in_array($_FILES['upimage']['type'],$fileext)){
					$errors[]="你上传的文件格式不正确,仅支持 png, jpg, gif格式。";
				}
if($im = @imagecreatefrompng($_FILES['upimage']['tmp_name']) or 
$im = @imagecreatefromgif($_FILES['upimage']['tmp_name']) 
or $im = @imagecreatefromjpeg($_FILES['upimage']['tmp_name'])){
$imginfo = @getimagesize($_FILES['upimage']['tmp_name']);
					if(!is_array($imginfo)){
						$errors[]="图像格式错误!";
					}
					if(empty($errors)){
						switch($_POST['size']){
							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 ( 'application.extensions.ico.phpthumb_ico', 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.'/upload/ico/';
						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,'',$filePath);
						}
					}
				}else{
					$errors[]="生成错误请重试!";
				}
			}
		}
		$this->render ( 'ico',array('output'=>$output,'errors'=>$errors));
	}

3,前台

<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 ( 'CActiveForm', array (
		'id' => 'ico-form',
		'htmlOptions' => array (
				'id' => 'view_table',
				'class' => 'add-form padding-10',
				'enctype'=>'multipart/form-data'
		),
		'action'=>'/tool/ico?action=make',
		'enableAjaxValidation' => 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="$('input[id=upimage]').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 ( 'CActiveForm', array (
				'id' => 'ico-form',
				'htmlOptions' => array (
						'id' => 'view_table',
						'class' => 'add-form padding-10',
				),
				'action'=>'/tool/icoDownload',
				'enableAjaxValidation' => false
		) );
		?>
		<?php echo CHtml::hiddenField('filePath',$output);?>
		<p class="form-group">
			<label class="col-lg-2 text-right">成功生成</label>
			<p class="col-lg-5">
		<img alt="在线制作ICO图标_favicon.ico" src="<?php echo $output;?>" 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 -->

效果图:

1004.jpg

以上就介绍了PHP生成ICO图标使用phpthumb_ico类完整实例,包括了上传文件方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

php

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
讯飞智文

一款面向学习和办公场景的AI文档创作工具,可辅助生成PPT与Word文档,提高资料整理和内容制作效率。

立刻MV
立刻MV Hot

立刻MV是一款AI文本写作工具,AI 音乐视频(MV)创作工具。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

火山引擎

火山引擎是一款面向企业的云计算与AI服务平台。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

讯飞智作

讯飞智作是一款AI视频创作工具,AI文本配音工具,数字人课程、营销视频制作。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

PixTV
PixTV Hot

PixTV是一款面向AIGC内容创作的AI视频生成工具。

二狗PPT
二狗PPT Hot

一款AI演示文稿工具,主要用于专为中式职场打造的AI PPT生成工具,适合需要提升相关任务效率的用户。

相关专题

更多
Navicat创建数据库教程
Navicat创建数据库教程

本专题整理Navicat创建数据库相关教程,介绍新建前的准备、基础设置和创建后的检查方法。内容兼顾入门学习及实际使用需求,帮助用户了解不同数据库类型下的操作差异,为后续建表、保存数据和日常管理提供参考。

20

2026.11.20

Navicat入门教程大全
Navicat入门教程大全

本专题整理Navicat入门教程,从认识软件界面到开展数据库操作,介绍初次使用需要了解的知识和方法。内容兼顾连接配置、数据管理及日常使用中的疑问,方便用户按学习进度查阅,为后续实践和独立操作打好基础。

20

2026.11.20

Navicat数据库连接配置指南
Navicat数据库连接配置指南

从确认数据库信息到建立可用连接,本专题串联Navicat连接数据库的相关知识和操作方法。既有初次配置时需要了解的基础内容,也有连接后的检查思路,方便用户按实际需求查阅教程,逐步熟悉数据库连接的设置流程。

0

2026.11.20

PHP8.6数组与数据处理教程
PHP8.6数组与数据处理教程

本专题汇总PHP8.6数组与数据处理教程,涵盖CSV读取和导出、引用遍历删除、array_filter回调模式、配置键名冲突、pathinfo文件名校验、GMP大整数进制转换及UTF-8正则筛选,说明升级兼容变化、输入范围和失败处理方法。

60

2026.11.20

PHP8.6升级迁移教程
PHP8.6升级迁移教程

本专题汇总PHP8.6升级迁移与弃用接口改造教程,涵盖反射调用、对象属性赋值、标识符更名、构造函数与__debugInfo调整,以及插件类名检查、常量导出、ArrayIterator排序、SPL和DTO查询参数转换,帮助梳理弃用提示并完成代码兼容改造。

0

2026.11.20

PHP8.6安装配置与FPM运维教程
PHP8.6安装配置与FPM运维教程

本专题汇总PHP8.6正式版安装部署与FPM运维教程,涵盖Linux并存安装、独立ini配置、扩展重新编译、Nginx切换与回滚、FPM状态监控和慢日志排查,以及环境变量、请求超时、OPcache刷新和预加载配置。

40

2026.11.20

Nginx CVE-2026-123007排查与防护指南
Nginx CVE-2026-123007排查与防护指南

Nginx HTTP/2漏洞该怎么修复?本专题围绕CVE-2026-123007,介绍安全版本升级、模块兼容检查和配置恢复方法,以及日志排查、权限设置等后续加固操作,方便你按实际部署情况查找对应教程。

40

2026.11.20

GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

80

2026.11.17

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

100

2026.11.17

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
墨刀帮助中心
墨刀帮助中心

共0课时 | 0人学习

MyEclipse学习中心
MyEclipse学习中心

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn