Spaces:
Sleeping
Sleeping
File size: 2,568 Bytes
e0a7f38 6933ad0 655ca0f e0a7f38 f6ef993 a2eb1d6 6933ad0 6006601 a2eb1d6 0989a67 f6ef993 6933ad0 b8472b1 6933ad0 655ca0f 6933ad0 f6ef993 6933ad0 a2eb1d6 690bb8e 6933ad0 690bb8e b8472b1 6006601 690bb8e b8472b1 690bb8e b8472b1 690bb8e 6006601 faf7748 690bb8e 6933ad0 84cfcc7 6933ad0 6006601 b8472b1 e0a7f38 a2eb1d6 e31f3af e0a7f38 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
const express = require('express');
const fetch = require('node-fetch');
const FormData = require('form-data');
const sharp = require('sharp');
const app = express();
app.get('/resize', async (req, res) => {
const imageUrl = req.query.q;
const size = parseInt(req.query.s, 10) || 100; // 默认值为 100
if (!imageUrl) {
console.error('没有提供图像 URL');
return res.status(400).send('没有提供图像 URL');
}
if (isNaN(size) || size <= 0) {
console.error('无效的大小参数');
return res.status(400).send('无效的大小参数');
}
try {
const response = await fetch(imageUrl);
if (!response.ok) {
throw new Error(`获取图像失败: ${response.statusText}`);
}
const imageBuffer = await response.buffer();
console.log('原始图像大小:', imageBuffer.byteLength);
// 使用 sharp 库来调整图像大小
const resizedImageBuffer = await sharp(imageBuffer).resize(size).toBuffer();
console.log('压缩后的图像大小:', resizedImageBuffer.byteLength);
// 将压缩后的图像转换为 Base64 编码的数据
const base64Image = resizedImageBuffer.toString('base64');
// 创建一个 FormData 对象并添加压缩后的图像
// const formData = new FormData();
// formData.append('file', resizedImageBuffer, { filename: 'compressed.jpg', contentType: 'image/jpeg' });
// 使用新的 API 地址和方法上传文件
// const uploadResponse = await fetch('https://ours.pages.dev/upload', {
// method: 'POST',
// body: formData
// });
// if (!uploadResponse.ok) {
// throw new Error(`上传图像失败: ${uploadResponse.statusText}`);
// }
// const uploadResult = await uploadResponse.text();
// console.log('上传结果:', uploadResult);
// Parse the JSON response and construct the full URL
// const uploadResultJson = JSON.parse(uploadResult);
// const fullUrl = `https://ours.pages.dev${uploadResultJson[0].src}`;
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Max-Age', '86400');
res.send(base64Image);
} catch (error) {
console.error('压缩图像时出错:', error);
res.status(500).send('压缩图像时出错');
}
});
const PORT = process.env.PORT || 7860;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
|