PHP generate ICO icon using Phpthumb_ico class complete instance

Source: Internet
Author: User
Tags transparent color php foreach yii
Here I am using the YII framework.

1,phpthumb_ico is the class that generates the ICO icon, the source code is as follows

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] = = (+) {$icXOR [$key]. = Chr ($b). chr ($g) Chr ($r). chr ($a); } elseif ($bpp [$key] = = 24{$icXOR [$key]. = Chr ($b). chr ($g). chr ($R);                    if ($a <) {@ $icANDmask [$key] [$y]. = ' 1 ';                    } else {@ $icANDmask [$key] [$y]. = ' 0 '; }}//Mask bits is 32-bit aligned per scanline while (strlen ($icANDmask [$ke                y][$y]) {$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 I          F >=8bpp) $icondata. = "\x00";       breserved;            Reserved (must be 0) $icondata. = "\x01\x00";         Wplanes; Color Planes $iCondata. = Chr ($bpp [$key]). "   \x00 ";       Wbitcount; Bits per pixel $dwBytesInRes = + strlen ($icXOR [$key]) + strlen ($icAND [$key]); $icondata. = $this->littleendian2s Tring ($dwBytesInRes, 4);//dwbytesinres;//How many bytes in this resource? $icondata. = $this->littleendian2string ($            Dwimageoffset, 4);//dwimageoffset;//Where in the are 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, backstage

Introduction class:

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

Solve the problem of generating a black background

Imagealphablending ($resize _im, false);//Do not merge color, directly replace with $im image color, including transparent color Imagesavealpha ($resize _im, true);//Don't Lose $resize_ The complete method of transparent color for IM images:

Complete method:

/** * icomaker online Generate ico icon * @author flashalliance */public function Actionico () {$this->breadcrumbs=array_merge ($this- >breadcrumbs,array (' ico icon Maker '); $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 []=] The file you uploaded is too large, Maximum no more than 200K. ";} $fileext = Array ("Image/pjpeg", "Image/jpeg", "Image/gif", "Image/x-png", "image/png"); if (!in_array ($_files[') Upimage ' [' type '], $fileext) {$errors []=] The file format you uploaded is incorrect and only supports PNG, JPG, GIF format. ";} 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 ') (!is_array ($imginfo)) {$errors []=] image format Error! ";} 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);//Do not merge color, directly replace with $im image color, including transparent color Imagesavealpha ($resize _im, true);//Don't Lose $resize_ The transparent color of the IM image solves the problem of generating a black background 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 []=] Build error please try again! ";}}} $this->render (' ico ', array (' output ' = $output, ' errors ' + $errors));}

3, front desk

<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> online production ico icon </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" > Upload file </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 (); > select File </a>&Lt;/p></p></p><p class= "Form-group" ><label class= "col-lg-2 text-right" > select size </label ><p class= "col-lg-5 btn-group" data-toggle= "buttons" > <label class= "btn btn-sm btn-default" > <input t Ype= "Radio" name= "Size" id= "S1" value= "1" checked= "checked" > 16*16 </label> <label class= "btn btn-sm btn-d Efault "> <input type=" Radio "name=" size "id=" S2 "value=" 2 "> 32*32 </label> <label class=" Btn BT N-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" > Support format </label><p class= "Col-lg-5" > Png,jpg,gif</p></p><p class= "list_back" ><input type= "submit" value= "Generate" 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> build result </p><p class=" Clearfix "> </p></p><?php if (!empty ($errors)):? ><p class= "Form-group" ><label class= "col-lg-2 Text-right "> Build failed </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" > successfully generated </label><p class= "Col-lg-5" > "class=" margin-r-10 "><input type=" submit "value=" Download Now "class=" btn btn-sm btn-success margin-l-10 "></ p></p><?php $this->endwidget ();? ><?php endif;? ></p><?php endif;? ></p><!--Form--

The above describes the PHP generation ICO icon using the Phpthumb_ico class complete instance, including the content of uploading files, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.