杜郎俊赏 - dujun.io

建站之图片缩略图

难点在于,gif 图片直接截缩略图可能有巨大噪音,所以改为截取第一帧。

//生成缩略图
public static function createThumb($imagePath)
{
    try {
        if (!($imagePath = File::exist($imagePath))) {
            return false;
        }

        if (is_mobile()) {
            //移动端生成更小的图
            $path = $imagePath . '_s.jpg';
            $maxWidth = 147;
        } else {
            $path = $imagePath . '_m.jpg';
            $maxWidth = 294;
        }
        $maxHeight = 500;

        $imagick = new Imagick($imagePath);
        $width = $imagick->getImageWidth();
        $height = $imagick->getImageHeight();

        while (1) {
            if ($maxWidth < $width) {
                $height = $height * $maxWidth / $width;
                $width = $maxWidth;
            } elseif ($maxHeight < $height) {
                $width = $width * $maxHeight / $height;
                $height = $maxHeight;
            } else {
                break;
            }
        }

        if (GIF == strtolower($imagick->getImageFormat()) && 400 > $imagick->count()) {
            //截取 gif 第一帧
            foreach ($imagick->coalesceImages() as $frame) {
                $tmp = new Imagick();
                $tmp->readImageBlob($frame);
                $imagick = $tmp;
                break;
            }
        }

        $imagick->thumbnailImage(format_integer($width), 0);
        $imagick->setImageCompressionQuality(60);
        $imagick->writeImage($path);
        $imagick->destroy();
        if (isset($tmp)) {
            $tmp->destroy();
        }

        return $path;
    } catch (Exception $e) {
    }
}

标签: 建站
日期:2017-05-18