|
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; |
|
|
|
if (!imageUrl) { |
|
console.error('没有提供图像 URL'); |
|
return res.status(400).send('没有提供图像 URL'); |
|
} |
|
|
|
try { |
|
const response = await fetch(imageUrl); |
|
if (!response.ok) { |
|
throw new Error(`获取图像失败: ${response.statusText}`); |
|
} |
|
const imageBuffer = await response.buffer(); |
|
console.log('原始图像大小:', imageBuffer.byteLength); |
|
|
|
|
|
const resizedImageBuffer = await sharp(imageBuffer).resize(100).toBuffer(); |
|
console.log('压缩后的图像大小:', resizedImageBuffer.byteLength); |
|
|
|
|
|
const formData = new FormData(); |
|
formData.append('file', resizedImageBuffer, { filename: 'compressed.jpg', contentType: 'image/jpeg' }); |
|
|
|
|
|
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); |
|
|
|
|
|
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(fullUrl); |
|
} 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}`); |
|
}); |
|
|