typecho中,没有压缩图片或者转格式的,这个就是一个代码,将代码复制,保存为ImageOptimize.php,可以根据以下代码,创建一个插件。
<?php
/**
* Typecho ImageOptimize Plugin
* 自动将上传的 JPG/PNG 转为 WebP,生成响应式缩略图
* 作者:typhonius
* 适配:Typecho 1.2+
*/
class ImageOptimize_Plugin implements Typecho_Plugin_Interface
{
public static function activate()
{
Typecho_Plugin::factory('Widget_Upload')->uploadFile = array('ImageOptimize_Plugin', 'optimizeUpload');
Typecho_Plugin::factory('Widget_Upload')->deleteFile = array('ImageOptimize_Plugin', 'deleteOptimized');
}
public static function deactivate() {}
public static function config(Typecho_Widget_Helper_Form $form)
{
$maxWidth = new Typecho_Widget_Helper_Form_Element_Text('maxWidth', null, '1200', _t('最大宽度'), _t('建议设置为1200,匹配博客内容宽度'));
$form->addInput($maxWidth);
$quality = new Typecho_Widget_Helper_Form_Element_Select('quality', array('70' => '70%', '80' => '80%', '90' => '90%'), '80', _t('压缩质量'));
$form->addInput($quality);
$convertWebp = new Typecho_Widget_Helper_Form_Element_Checkbox('convertWebp', array('1' => _t('启用WebP转换')), '1', _t('WebP转换'));
$form->addInput($convertWebp);
$deleteOriginal = new Typecho_Widget_Helper_Form_Element_Checkbox('deleteOriginal', array('1' => _t('删除原图')), '1', _t('节省空间,建议开启'));
$form->addInput($deleteOriginal);
}
public static function personalConfig(Typecho_Widget_Helper_Form $form) {}
public static function optimizeUpload($file, $type, $name, $path)
{
$config = Typecho_Widget::widget('Widget_Options')->plugin('ImageOptimize');
if (!$config->convertWebp) return $file;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (!in_array($ext, ['jpg', 'jpeg', 'png'])) return $file;
$webpPath = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $file);
$image = imagecreatefromstring(file_get_contents($file));
$width = imagesx($image);
$height = imagesy($image);
if ($width > $config->maxWidth) {
$newWidth = $config->maxWidth;
$newHeight = ($height * $newWidth) / $width;
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($newImage, $webpPath, $config->quality);
imagedestroy($newImage);
} else {
imagejpeg($image, $webpPath, $config->quality);
}
imagedestroy($image);
if ($config->deleteOriginal) unlink($file);
return $webpPath;
}
}学习代码。