<?php

/**
 * 图片工具
 * Class ImageTool
 */
class ImageTool
{
    /**
     * 获取图片信息
     * @param $filename
     * @return array|false
     */
    public static function getImageSize($filename)
    {
        return getimagesize($filename);
    }

    /**
     * 创建空白图片资源
     * @param $width
     * @param $height
     * @return false|GdImage|resource
     */
    public static function createResource($width, $height)
    {
        return imagecreatetruecolor($width, $height);
    }

    /**
     * 创建图片资源
     * @param $filename
     * @return false|GdImage|resource|null
     */
    public static function createResourceFromFile($filename)
    {
        $imageSize = self::getImageSize($filename);
        switch ($imageSize['mime']) {
            case 'image/jpeg':
                $resource = imagecreatefromjpeg($filename);
                break;
            case 'image/png':
                $resource = imagecreatefrompng($filename);
                break;
            case 'image/gif':
                $resource = imagecreatefromgif($filename);
                break;
            default:
                $resource = null;
        }

        return $resource;
    }

    /**
     * 合并图片
     * @param $resource
     * @param $addResource
     * @param array $options
     * @return mixed
     */
    public static function merge(&$resource, $addResource, $options = [])
    {
        $options = array_merge([
            'position' => [0, 0],
        ], $options);
        imagecopy(
            $resource,
            $addResource,
            $options['position'][0],
            $options['position'][1],
            0,
            0,
            imagesx($addResource),
            imagesy($addResource)
        );

        return $resource;
    }

    /**
     * 为图片添加文字
     * @param $resource
     * @param string $text
     * @param array $options
     * @return mixed
     */
    public static function text(&$resource, $text = '', $options = [])
    {
        $options         = array_merge([
            'font'     => __DIR__ . '/font.ttf',
            'color'    => [255, 255, 255],
            'size'     => 20,
            'position' => [25, 20],
        ], $options);
        $color           = call_user_func_array(
            'imagecolorallocate',
            array_merge([$resource], $options['color'])
        );
        $currentEncoding = mb_detect_encoding($text);
        if ($currentEncoding != 'UTF-8') {
            $text = iconv($currentEncoding, 'UTF-8', $text);
        }
        imagettftext($resource, $options['size'], 0, $options['position'][0], $options['position'][1], $color, $options['font'], $text);

        return $resource;
    }

    /**
     * 修改图片/资源大小
     * @param $filename
     * @param $width
     * @param $height
     * @param false $crop
     * @return false|GdImage|resource
     */
    public static function resize($filename, $width, $height, $crop = false)
    {
        if (is_resource($filename)) {
            $size     = [imagesx($filename), imagesy($filename)];
            $resource = $filename;
        } else {
            $size     = self::getImageSize($filename);
            $resource = self::createResourceFromFile($filename);
        }
        // 宽高比
        $resourceProp = $size[1] / $size[0];
        $targetProp   = $height / $width;

        if ($resourceProp > $targetProp) {
            $targetWidth  = $width;
            $targetHeight = $width * $resourceProp;
        } else if ($resourceProp < $targetProp) {
            $targetHeight = $height;
            $targetWidth  = $height / $resourceProp;
        } else {
            $targetWidth  = $width;
            $targetHeight = $height;
        }
        // 创建资源
        $targetResource = self::createResource($targetWidth, $targetHeight);
        // 缩放
        imagecopyresampled($targetResource, $resource, 0, 0, 0, 0, $targetWidth, $targetHeight, $size[0], $size[1]);
        // 裁剪
        if (true === $crop) {
            // 居中
            $sourceX      = ($targetWidth - $width) / 2;
            $sourceY      = ($targetHeight - $height) / 2;
            $cropResource = self::createResource($width, $height);
            imagecopy($cropResource, $targetResource, 0, 0, $sourceX, $sourceY, $width, $height);

            return $cropResource;
        }

        return $targetResource;
    }

    /**
     * 图片圆角处理
     * @param $resource
     * @param int $size
     */
    public static function radius(&$resource, $size = 10)
    {
        $w = imagesx($resource);
        $h = imagesy($resource);
        if (empty($size)) {
            $radius = min($w, $h) / 2;
        } else {
            $radius = $size / 2;
        }
        $img = imagecreatetruecolor($w, $h);
        imagesavealpha($img, true);
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $radius;
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($resource, $x, $y);
                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                } else {
                    $yx = $r;
                    $yy = $r;
                    if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    $yx = $w - $r;
                    $yy = $r;
                    if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    $yx = $r;
                    $yy = $h - $r;
                    if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    $yx = $w - $r;
                    $yy = $h - $r;
                    if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                }
            }
        }

        $resource = $img;
    }

    /**
     * 保存图片
     * @param $resource
     * @param $filename
     * @return bool
     */
    public static function save($resource, $filename)
    {
        $fileNameArr = explode('.', $filename);
        $fileExt     = strtolower(end($fileNameArr));
        unset($fileNameArr);

        switch ($fileExt) {
            case 'jpg':
            case 'jpeg':
                return imagejpeg($resource, $filename);
            case 'png':
                return imagepng($resource, $filename);
            case 'gif':
                return imagegif($resource, $filename);
            default:
        }

        return false;
    }
}