$aliossConfig['accessKeyId'], 'endpoint' => $aliossConfig['endpoint'], 'bucket' => $aliossConfig['bucket'], 'region' => str_replace('-internal', '', substr(explode('.', $aliossConfig['endpoint'])[0], 4)), 'provider' => new \OSS\Credentials\StaticCredentialsProvider($aliossConfig['accessKeyId'], $aliossConfig['accessKeySecret']), 'signatureVersion' => \OSS\OssClient::OSS_SIGNATURE_VERSION_V4, ]); $pdo = new PDO('mysql:host=127.0.0.1;port=3307;dbname=fenleixinxi;charset=utf8mb4', 'fenleixinxi', 'fenleixinxi'); $cdn = rtrim($aliossConfig['cdnurl'] ?? 'https://tjxc-xinxi.oss-cn-shenzhen.aliyuncs.com', '/'); // 查询所有大于 100KB 的历史大图附件 $stmt = $pdo->query("SELECT id, url, filesize, imagewidth, imageheight FROM fa_attachment WHERE storage = 'alioss' AND filesize > 100000"); $list = $stmt->fetchAll(PDO::FETCH_ASSOC); echo "发现需要瘦身的历史大图附件: " . count($list) . " 个\n"; $tmpDir = ROOT_PATH . 'tmp_img' . DS . 'shrink_tmp'; if (!is_dir($tmpDir)) @mkdir($tmpDir, 0755, true); $done = 0; foreach ($list as $att) { $ossKey = ltrim($att['url'], '/'); $imgUrl = $cdn . '/' . $ossKey; $rawFile = $tmpDir . DS . 'raw.jpg'; $thumbFile = $tmpDir . DS . 'thumb.jpg'; // 1. 下载原图 $content = @file_get_contents($imgUrl); if (!$content) continue; file_put_contents($rawFile, $content); // 2. 缩放到 240x240 $srcImg = @imagecreatefromstring($content); if (!$srcImg) { @unlink($rawFile); continue; } $w = imagesx($srcImg); $h = imagesy($srcImg); $thumbImg = imagecreatetruecolor(240, 240); imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, 240, 240, $w, $h); imagejpeg($thumbImg, $thumbFile, 82); imagedestroy($srcImg); imagedestroy($thumbImg); @unlink($rawFile); $newSize = filesize($thumbFile); if ($newSize < 1000) { @unlink($thumbFile); continue; } // 3. 覆盖推送回 OSS try { $oss->uploadFile($aliossConfig['bucket'], $ossKey, $thumbFile); // 4. 更新附件表尺寸与大小 $upStmt = $pdo->prepare("UPDATE fa_attachment SET filesize = ?, imagewidth = 240, imageheight = 240 WHERE id = ?"); $upStmt->execute([$newSize, $att['id']]); @unlink($thumbFile); $done++; if ($done % 20 === 0) { echo "已成功瘦身覆盖 $done / " . count($list) . " 张 (当前大小约 " . round($newSize/1024) . "KB)\n"; } } catch (\Exception $e) { @unlink($thumbFile); } } echo "历史大图瘦身完成!共成功处理: $done 张\n";