<?php
declare (strict_types=1);
namespace library\utils;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-11-15 20:30
// +----------------------------------------------------------------------

namespace library\utils;


class Icon
{


    public function mkIcon($img,$new_img) {
        $exp = strtoupper(substr(strrchr($img, '.'), 1));
        //下载图片
        $data = $this->httpcopy($img,app()->getRootPath()."public/public/tmp/"
            .md5($img .time()).'.'.$exp);
        $img = $data['fileName'];
        if(empty($img)) return null;
        $new_img = $new_img . md5($img) . '_favicon.ico';
        if($exp == 'PNG') {
            $im = @imagecreatefrompng($img);
            imagesavealpha($im,true);
            $img_func = 'imagepng';
        }
        if($exp == 'JPG' || $exp == 'JPEG') {
            $im = @imagecreatefromjpeg($img);
            $img_func = 'imagejpeg';
        }
        if($exp == 'GIF') {
            $im = @imagecreatefromgif($img);
            $img_func = 'imagegif';
        }
        $quality = 100;//图片质量
        if($img_func == 'imagepng')
        {
            $quality = 9;
        }
        $imginfo = @getimagesize($img);
        $size = 64;
        $resize_im = @imagecreatetruecolor(64,64);
        $color = imagecolorallocatealpha($resize_im,0, 0, 0, 127);
        imagefill($resize_im,0,0,$color);
        imagecopyresampled($resize_im,$im,0,0,0,0,$size,$size,$imginfo[0],$imginfo[1]);
        imagesavealpha($resize_im,true);
        call_user_func_array($img_func,array($resize_im,app()->getRootPath() . 'public/' . $new_img,$quality));
        imagedestroy($resize_im);//清除句柄
        imagedestroy($im);//清除句柄
        @unlink($img);
        return ['root_img'=>app()->getRootPath() . $new_img,'img'=>$new_img];
    }


    /**
     * 生成down
     * @param $url
     * @param $file
     * @return null
     */
    private function  httpcopy($url,$file){
        $result = [];
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_TIMEOUT,60);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
        $temp=curl_exec($ch);
        if(@file_put_contents($file,$temp) &&!curl_error($ch)){
            $result['fileName']=$file;
            $result['way']='curl';
            $result['size']=sprintf('%.3f',strlen($temp)/1024);
        }
        return $result;
    }
}
