
<?php
require dirname(__FILE__, 2) . '/vendor/autoload.php';
$secretId = "SECRETID"; //替换为用户的 secretId,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
$secretKey = "SECRETKEY"; //替换为用户的 secretKey,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
$region = "ap-beijing"; //替换为用户的 region,已创建桶归属的region可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket
$cosClient = new Qcloud\Cos\Client(
array(
'region' => $region,
'scheme' => 'https', //协议头部,默认为http
'credentials'=> array(
'secretId' => $secretId,
'secretKey' => $secretKey)));
$local_path = "/data/exampleobject";
//添加tagging
/*$tagSet = http_build_query( array(
urlencode("key1") => urlencode("value1"),
urlencode("key2") => urlencode("value2")),
'',
'&'
); */
try {
$result = $cosClient->putObject(array(
'Bucket' => 'examplebucket-125000000', //存储桶名称,由BucketName-Appid 组成,可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
'Key' => 'exampleobject',
'Body' => fopen($local_path, 'rb'),
/*
'CacheControl' => 'string',
'ContentDisposition' => 'string',
'ContentEncoding' => 'string',
'ContentLanguage' => 'string',
'ContentLength' => integer,
'ContentType' => 'string',
'Expires' => 'string',
'Metadata' => array(
'string' => 'string',
),
'StorageClass' => 'string',
'Tagging' => $tagSet //最多10个标签
*/
));
// 请求成功
print_r($result);
} catch (\Exception $e) {
// 请求失败
echo($e);
}
源码:https://github.com/tencentyun/cos-php-sdk-v5/blob/master/sample/putObject.php
运行此代码需要使用腾讯云提供的 cos-php-sdk-v5,我们用源码方式下载就行,去 release 界面将.tar.gz 的包下载到本地,然后在 sample 内就可以找到这个文件。
配置工作流
接下来就是如何实现在上传时给图片自动加水印了。
官方文档:https://cloud.tencent.com/document/product/436/53967
进入 Cos 控制台,然后按照文档中的找到工作流,然后创建。
工作流名称可以填“博客图片上传自动加水印”,格式匹配选图片文件。
点击输入后的“+”号,进入图片处理页面。存储桶选你的图床,目标文件名填 ${InputName}.webp,目标路径默认,然后去新建一个图片处理模板。
这里的目标文件名这么填的原因是,工作流有点相当于一个任务钩子,在上传图片完成后触发。而 Typecho 要利用我们上传图片完成后,cos 返回给 typecho 的链接来引用图片。所以我们的这个工作流实际上是将文件处理后将原文件覆盖。


private static function isImageExt(string $ext): bool
{
return in_array(strtolower($ext), [
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'
], true);
}
private static function uploadImageWithWatermark(
$cosClient,
string $bucket,
string $uploadfile,
string $path
): void {
$cosClient->putObject([
'Bucket' => $bucket,
'Key' => $path,
'Body' => fopen($uploadfile, 'rb'),
'PicOperations' => "",
]);
}
private static function uploadNormalFile(
$cosClient,
string $bucket,
string $uploadfile,
string $path
): void {
$cosClient->upload(
$bucket,
$path,
fopen($uploadfile, 'rb'),
[
'ACL' => 'public-read',
'CacheControl' => 'private',
]
);
}
/**
* @description: 上传文件处理函数
* @param {array} $file
* @return {*}
* @throws Exception
*/
public static function uploadHandle(array $file)
{
if (empty($file['name'])) {
return false;
}
// 原始扩展名
$originExt = self::getSafeName($file['name']);
if (!\Widget\Upload::checkFileType($originExt)) {
return false;
}
$opt = Options::alloc()->plugin(pluginName);
$date = new \Typecho\Date($opt->gmtTime);
$fileDir = self::getUploadDir() . $date->year . '/' . $date->month;
// 是否图片
$isImage = self::isImageExt($originExt);
// 图片统一存成 webp
$ext = $isImage ? 'webp' : $originExt;
$fileName = sprintf('%u', crc32(uniqid())) . '.' . $ext;
$path = $fileDir . '/' . $fileName;
$uploadfile = self::getUploadFile($file);
if (!isset($uploadfile)) {
return false;
}
$cosClient = self::CosInit();
try {
// 防止重名
$times = 10;
while ($times > 0 && self::doesObjectExist($path)) {
$fileName = sprintf('%u', crc32(uniqid($times--))) . '.' . $ext;
$path = $fileDir . '/' . $fileName;
}
if ($isImage) {
self::uploadImageWithWatermark(
$cosClient,
$opt->bucket,
$uploadfile,
$path
);
} else {
self::uploadNormalFile(
$cosClient,
$opt->bucket,
$uploadfile,
$path
);
}
} catch (\Exception $e) {
echo $e;
return false;
}
// 补 size
if (!isset($file['size'])) {
$info = $cosClient->headObject([
'Bucket' => $opt->bucket,
'Key' => $path
])->toArray();
$file['size'] = $info['ContentLength'];
}
// 本地备份(注意:图片这里是原图,不是 webp)
if ($opt->local === 'open' && self::makeUploadDir($fileDir)) {
@move_uploaded_file($uploadfile, $path);
}
return [
'name' => $file['name'],
'path' => $path,
'size' => $file['size'],
'type' => $ext,
'mime' => \Typecho\Common::mimeContentType($path),
];
}
自己记得格式化一下。源码的作用是为了给上传图片和其他附件做个区分,最主要的是确保上传后的后缀名为 webp。因为我们上传的文件不一定是什么格式的,用这种方式能确保上传后的图片是 webp,从而让工作流能够覆盖源文件。
什么是 Webp?
WebP 是一种新型图片格式,可为网络上的图片提供品质卓越的无损和有损压缩。使用 WebP,网站站长和网络开发者可以创建体积更小但细节更丰富的图片,从而提高网络访问速度。
WebP 无损图片比 PNG 图片小 26%。WebP 有损图片比采用等效 SSIM 质量指标的同等 JPEG 图片缩小 25-34%。