Spaces:
Sleeping
Sleeping
Create index.js
Browse files
index.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const fetch = require('node-fetch');
|
| 3 |
+
const sharp = require('sharp');
|
| 4 |
+
|
| 5 |
+
const app = express();
|
| 6 |
+
|
| 7 |
+
app.get('/resize', async (req, res) => {
|
| 8 |
+
const imageUrl = req.query.q;
|
| 9 |
+
|
| 10 |
+
if (!imageUrl) {
|
| 11 |
+
console.error('没有提供图像 URL');
|
| 12 |
+
return res.status(400).send('没有提供图像 URL');
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
try {
|
| 16 |
+
const response = await fetch(imageUrl);
|
| 17 |
+
if (!response.ok) {
|
| 18 |
+
throw new Error(`获取图像失败: ${response.statusText}`);
|
| 19 |
+
}
|
| 20 |
+
const imageBuffer = await response.buffer();
|
| 21 |
+
console.log('原始图像大小:', imageBuffer.byteLength);
|
| 22 |
+
|
| 23 |
+
// 使用 sharp 库来调整图像大小
|
| 24 |
+
const resizedImageBuffer = await sharp(imageBuffer).resize(100).toBuffer();
|
| 25 |
+
console.log('压缩后的图像大小:', resizedImageBuffer.byteLength);
|
| 26 |
+
|
| 27 |
+
// 将压缩后的图像转换为 Base64 编码的数据
|
| 28 |
+
const base64Image = resizedImageBuffer.toString('base64');
|
| 29 |
+
|
| 30 |
+
res.setHeader('Content-Type', 'text/plain');
|
| 31 |
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
| 32 |
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
| 33 |
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
| 34 |
+
res.setHeader('Access-Control-Max-Age', '86400');
|
| 35 |
+
res.send(base64Image);
|
| 36 |
+
} catch (error) {
|
| 37 |
+
console.error('压缩图像时出错:', error);
|
| 38 |
+
res.status(500).send('压缩图像时出错');
|
| 39 |
+
}
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
const PORT = process.env.PORT || 7860;
|
| 43 |
+
app.listen(PORT, () => {
|
| 44 |
+
console.log(`Server is running on port ${PORT}`);
|
| 45 |
+
});
|