当前是接入网页的效果
首先表示感谢
感谢laf提供赞助,目前可以免费使用Midjourney进行开发和测试。
感谢白夜、米开朗基杨@sealos.io的耐心解答
准备工具
- laf.dev
- Midjourney账号(加入laf可以免费提供)
- 前端源码(文章末尾)
- laf端Midjourney-api源码(在下面)
①打开laf.dev laf.dev
新建一个函数为api
将下列代码复制到函数中
import cloud from '@lafjs/cloud'
const uuid = require('uuid');
import { Midjourney } from 'midjourney'
const client = new Midjourney(
process.env.DAVINCI_TOKEN,
process.env.SALAI_TOKEN,
process.env.SERVER_ID,
process.env.CHANNEL_ID
)
const OSS = require('ali-oss');
const db = cloud.database()
const aliyunClient = new OSS({
region: 'OSS地区',
accessKeyId: 'OSS的KEY',
accessKeySecret: 'OSS秘钥',
bucket: '桶的名称',
});
async function uploadImage(buffer, filename, mimetype) {
const now = new Date();
const year = now.getFullYear();
const month = ('0' + (now.getMonth() + 1)).slice(-2); // 月份从 0 开始,因此需要 +1
const day = ('0' + now.getDate()).slice(-2);
// 构造文件夹路径
const folderPath = `${year}/${month}/${day}`;
// 构造文件夹路径
const newPath = `${folderPath}/${filename}`;
const result = await aliyunClient.put(newPath, buffer, {
headers: { 'Content-Type': mimetype },
});
return result.url;
}
export default async function (ctx: FunctionContext) {
await client.start()
const imag = ctx.body.msg
const data = await client.Imagine(imag, (uri: string) => {
console.log("loading", uri);
});
const filename = uuid.v4() + '.png';
const fetch = (await import('node-fetch')).default;
const response = await fetch(data.uri);
const buffer = await response.buffer();
const contentType = response.headers.get('content-type');
data.uri = await uploadImage(buffer, filename, contentType);
return { data }
}
可以看到此函数中有生成图片方法
生成图片
curl --location --request POST 'https://<函数地址>' \
--header 'Content-Type: application/json' \
--data-raw '{
"msg": "生成图片的命令"
}'
②修改前端请求
准备环境
- -node 18
声明:技术薄弱,引用的 GitHub 上的源码修改的
找到云目录 index.tsx 放入我们的云函数地址
加入
const newImgUri = r.data.data.uri;
setImgs(prevImgs => [...prevImgs, { imgUrl: newImgUri, createdAt: new Date() }]);
运行 npm install
运行 npm run dev
访问localhost:3000
有问题 可以联系微信 一起探讨