<?php

declare(strict_types=1);

/**
 * @author：llbjj
 * @DateTime：2023/4/25 14:00
 * @Description：
 */

namespace Application\Common;

use Gumlet\ImageResize;

use Gumlet\ImageResizeException;
use function imagecolorallocate;
use function imagecolorallocatealpha;
use function imagecopy;
use function imagecreatetruecolor;
use function imagefilledrectangle;
use function imagerotate;
use function imagesx;
use function imagesy;
use function imagettfbbox;
use function imagettftext;
use function max;
use function min;
use const Application\Utils\APP_PATH;

class ImageResizeExtends extends ImageResize
{
    /**
     * Notes:
     *
     * DateTime: 2023/5/26 9:36
     *
     * @param float $angle 正数向左旋转，负数向右旋转
     * @return $this
     */
    public function rotate(float $angle): ImageResizeExtends
    {
        if (! $angle) {
            return $this;
        }

        // 设置旋转后的背景色
        $transparentBlack   = imagecolorallocatealpha($this->source_image, 0, 0, 0, 127);
        $this->source_image = imagerotate($this->source_image, $angle, $transparentBlack);
        // 重新获取原图片的宽
        $this->original_w = imagesx($this->source_image);
        // 重新获取原图片的高
        $this->original_h = imagesy($this->source_image);
        $this->resize($this->getSourceWidth(), $this->getSourceHeight());
        return $this;
    }

    public function outputLength($image_type = null, $quality = null, $filesize = 0)
    {
        $image_type = $image_type ?: $this->source_type;

        header('Content-Type: ' . image_type_to_mime_type($image_type));
        header('Content-Length: '. $filesize);
        $this->save(null, $image_type, $quality);
    }

    public static function createFromString($image_data)
    {
        if (empty($image_data) || $image_data === null) {
            throw new ImageResizeException('image_data must not be empty');
        }
        $resize = new self('data://application/octet-stream;base64,' . base64_encode($image_data));
        return $resize;
    }
}
