五分钟 实现chatgpt+Midjourney工具 出图ai 变现

这篇具有很好参考价值的文章主要介绍了五分钟 实现chatgpt+Midjourney工具 出图ai 变现。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

首先感谢laf提供免费使用Midjourney API接口和云函数,需要详细了解的可以访问他们的官网论坛。
感谢论坛前面几位的分享,我做了参考。都有参考就不列啦哈!!!

直接开始:

第一步

复制MJ-SEND云函数到laf云平台,并发布获得云函数访问地址“https://xxx.laf.dev/mj-sent”

import cloud from '@lafjs/cloud'
import { Midjourney, MidjourneyMessage } from 'midjourney'
const SERVER_ID = '' // Midjourney 服务 ID
const CHANNEL_ID = '' // Midjourney 频道 ID
const SALAI_TOKEN = '' // Midjourney 服务 Token
 
const Limit = 100
const MaxWait = 3
 
const client = new Midjourney({
  ServerId: SERVER_ID,
  ChannelId: CHANNEL_ID,
  SalaiToken: SALAI_TOKEN,
  Debug: true,
  SessionId: SALAI_TOKEN,
  Limit: Limit,
  MaxWait: MaxWait
});
 
export default async function (ctx: FunctionContext) {
  const { type, param } = ctx.body
  switch (type) {
    case 'RetrieveMessages':
      return await RetrieveMessages(param)
    case 'imagine':
      return await imagine(param)
    case 'upscale':
      return await upscale(param)
    case 'variation':
      return await variation(param)
  }
 
}
 
// 查询最近消息
async function RetrieveMessages(param) {
  console.log("RetrieveMessages")
  const client = new MidjourneyMessage({
    ChannelId: CHANNEL_ID,
    SalaiToken: SALAI_TOKEN,
  });
  const msg = await client.RetrieveMessages();
  console.log("RetrieveMessages success ", msg)
  return msg
}
 
// 创建生图任务
async function imagine(param) {
  console.log("imagine", param)
  const { question, msg_Id } = param
  const msg = await client.Imagine(
    `[${msg_Id}] ${question}`,
    (uri: string, progress: string) => {
      console.log("loading", uri, "progress", progress);
    }
  );
  console.log("imagine success ", msg)
  return true
}
 
// upscale 放大图片
async function upscale(param) {
  console.log("upscale", param)
  const { question, index, id, url } = param
  const hash = url.split("_").pop()?.split(".")[0] ?? ""
  console.log(hash)
  const msg = await client.Upscale(
    question,
    index,
    id,
    hash,
    (uri: string, progress: string) => {
      console.log("loading", uri, "progress", progress);
    }
  );
  console.log("upscale success ", msg)
  return msg
}
 
// variation 变换图片
async function variation(param) {
  console.log("variation", param)
  const client = new Midjourney({
    ServerId: SERVER_ID,
    ChannelId: CHANNEL_ID,
    SalaiToken: SALAI_TOKEN,
    Debug: true,
    SessionId: SALAI_TOKEN,
    Limit: Limit,
    MaxWait: 100
  });
  const { question, index, id, url } = param
  const hash = url.split("_").pop()?.split(".")[0] ?? ""
  const msg = await client.Variation(
    question,
    index,
    id,
    hash,
    (uri: string, progress: string) => {
      console.log("loading", uri, "progress", progress);
    }
  );
  console.log("variation success ", msg)
  return msg
}

第二步 写一个前端渲染效果

 <html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <script type="module" src="https://gradio.s3-us-west-2.amazonaws.com/3.19.1/gradio.js"></script>
    <!-- import vue -->
    <script src="https://unpkg.com/vue@next"></script>
    <!-- import Elm CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!-- import Elm JavaScript -->
    <script src="https://unpkg.com/element-plus"></script>
    <!-- import axios -->
    <script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>
    <title>mj</title>
    <style>
      body {
        display: flex;
        justify-content: center;
        background-color: #f5f5f5;
      }
      #app {
        width: 1000px;
      }
      .task {
        border: 1px solid #ddd;
        background-color: #fff;
        border-radius: 10px;
        margin-bottom: 20px;
        padding: 20px;
      }
      image {
        border-radius: 10px;
      }
    </style>
  </head>
  <body>
 
    <div id="app">
      <el-form>
        <el-form-item>
          <el-input type="textarea" v-model="question" placeholder="请输入要生成的图片内容,尽量使用英文"></el-input>
          <el-button style="margin-top: 10px;" type="primary" @click="submit" :loading="loading">提交</el-button>
        </el-form-item>
      </el-form>
      <div class="result" style="margin-top: 10px;">
        <h1>我的作品</h1>
        <div v-for="(item, index) in tasks" class="task" :key="item.msg_Id">
          <p>任务id: <el-button link type="primary">{{item.msg_Id}}</el-button> </p>
          <p>{{item.question}}</p>
          <p>
            <el-button type="primary" @click="getResult(item.msg_Id)">刷新</el-button>
          </p>
          <template v-if="item.result">
            <el-image fit="scale-down" lazy :src="item.result.url" :alt="item.question"></el-image>
            <p>
              <el-button type="primary" plain @click="variation(item, 1)">V1</el-button>
              <el-button type="primary" plain @click="variation(item, 2)">V2</el-button>
              <el-button type="primary" plain @click="variation(item, 3)">V3</el-button>
              <el-button type="primary" plain @click="variation(item, 4)">V4</el-button>
            </p>
            <p>
              <el-button type="primary" plain @click="upscale(item, 1)">U1</el-button>
              <el-button type="primary" plain @click="upscale(item, 2)">U2</el-button>
              <el-button type="primary" plain @click="upscale(item, 3)">U3</el-button>
              <el-button type="primary" plain @click="upscale(item, 4)">U4</el-button>
            </p>
            <template v-if="item.result.upscaleUrl">
              <h5>大图</h5>
              <el-image fit="scale-down" lazy :src="item.result.upscaleUrl" :alt="item.question"></el-image>
            </template>
          </template>
        </div>
        <h2>其他人的作品</h2>
        <div v-for="item in otherCase" :key="item.id" class="task">
          <h3>prompt:{{ formatPrompt(item.content) }}</h3>
          <h3>time:{{ formatDate(item.timestamp) }}</h3>
          <div v-for="attachment in item.attachments" :key="attachment.id">
            <el-image fit="scale-down" lazy :src="attachment.url" :alt="formatPrompt(item.content)"></el-image>
          </div>
        </div>
      </div>
    </div>
    <script>
      const App = {
        data() {
          return {
            question: "",
            msg_Id: "",
            loading: false,
            tasks: [],
            otherCase: []
          };
        },
        mounted() {
          this.initTask()
          this.getOtherCase()
        },
        methods: {
          initTask() {
            this.tasks = JSON.parse(window.localStorage.getItem('task') || JSON.stringify([]))
          },
          submit() {
            this.msg_Id = grs()
            this.loading = true
            axios({
              method: 'post',
              url: 'https://rpcqmo.laf.dev/mj-service',
              data: {
                type: 'imagine',
                param: {
                  msg_Id: this.msg_Id,
                  question: this.question
                }
              }
            }).then(res => {
              console.log('[ res ] >', res)
              this.$message.success("上传成功,正在画图,请稍后...")
              window.localStorage.setItem('task', JSON.stringify([
                { msg_Id: this.msg_Id, question: this.question, result: null },
                ...this.tasks
              ]))
              this.initTask()
              this.getResult(this.msg_Id)
            }).catch(err => {
              console.log('[ err ] >', err)
            }).finally(() => {
              this.loading = false
            })
          },
          getResult(msg_Id) {
            axios({
              method: 'post',
              url: 'https://rpcqmo.laf.dev/mj-service',
              data: {
                type: 'RetrieveMessages'
              }
            }).then(res => {
              console.log('[ res ] >', res)
              const { data } = res
              const resIndex = data.findIndex(item => item.content.includes(msg_Id))
              if (resIndex < 0) {
                this.$message.success('正在努力生成,请耐心等待')
                return
              }
              const { id, attachments } = data[resIndex]
              if (!attachments.length) {
                this.$message.success('正在努力生成,请耐心等待')
                return
              }
              const { url, width } = attachments[0]
              if (width >= 2048) {
                const myIndex = this.tasks.findIndex(item => item.msg_Id == msg_Id)
                this.tasks[myIndex].result = {
                  id,
                  url
                }
                window.localStorage.setItem('task', JSON.stringify(this.tasks))
              } else {
                this.$message.success('正在努力生成,请耐心等待')
                return
              }
            }).catch(err => {
              console.log('[ err ] >', err)
            }).finally(() => {
            })
          },
          variation({ result, question, msg_Id }, index) {
            console.log(result, question, index);
            this.$message.warning('努力开发中')
            return
            axios({
              method: 'post',
              url: 'https://rpcqmo.laf.dev/mj-service',
              data: {
                type: 'variation',
                param: {
                  id: result.id,
                  url: result.url,
                  question,
                  index
                }
              }
            }).then(res => {
            }).catch(err => {
              console.log('[ err ] >', err)
            }).finally(() => {
            })
          },
          upscale({ result, question, msg_Id }, index) {
            console.log(result, question, index);
            // this.$loading('正在生成大图')
            const loadingInstance = this.$loading({
              lock: true,
              text: '正在生成大图...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            axios({
              method: 'post',
              url: 'https://rpcqmo.laf.dev/mj-service',
              data: {
                type: 'upscale',
                param: {
                  id: result.id,
                  url: result.url,
                  question,
                  index
                }
              }
            }).then(res => {
              const { data } = res
              console.log('[ upscale data ] >', data)
              const taskIndex = this.tasks.findIndex(item => item.msg_Id == msg_Id)
              this.tasks[taskIndex].result.upscaleUrl = data.uri
              window.localStorage.setItem('task', JSON.stringify(this.tasks))
            }).catch(err => {
              console.log('[ err ] >', err)
            }).finally(() => {
              loadingInstance.close();
            })
          },
          getOtherCase() {
            axios({
              method: 'post',
              url: 'https://rpcqmo.laf.dev/mj-service',
              data: {
                type: 'RetrieveMessages'
              }
            }).then(res => {
              const { data } = res
              this.otherCase = data.filter(item => item.attachments.length)
            })
          },
          formatPrompt(str) {
            return str.substring(str.indexOf(']') + 1, str.indexOf('--seed')) + `(${str.substring(str.indexOf('[') + 1, str.indexOf(']'))})`
          },
          // 格式化日期时间
          padLeftZero(str) {
            return ('00' + str).substr(str.length);
          },
          formatDate(date, fmt = "yyyy-MM-dd hh:mm:ss") {
            if (/(y+)/.test(fmt)) {
              fmt = fmt.replace(RegExp.$1, (new Date(date).getFullYear() + '').substr(4 - RegExp.$1.length));
            }
            const o = {
              'M+': new Date(date).getMonth() + 1,
              'd+': new Date(date).getDate(),
              'h+': new Date(date).getHours(),
              'm+': new Date(date).getMinutes(),
              's+': new Date(date).getSeconds()
            }
            for (const k in o) {
              if (new RegExp(`(${k})`).test(fmt)) {
                const str = o[k] + '';
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str));
              }
            }
            return fmt;
          },
        }
      };
      const app = Vue.createApp(App);
      app.use(ElementPlus);
      app.mount("#app");
      function grs() {
        return 'Charlie-' + 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = Math.random() * 16 | 0,
              v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      }
    </script>
  </body>
</html>

第三步 上传服务器或者找个空间也可以本地访问文章来源地址https://www.toymoban.com/news/detail-511031.html

到了这里,关于五分钟 实现chatgpt+Midjourney工具 出图ai 变现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • AI绘画新的变现机会来了,Midjourney角色一致性重磅更新

    文章底部准备了变现方法和粉丝福利,看完后可免费领取! 一、功能更新介绍 昨天Midjourney发布了“角色一致性”算法,就是根据参考图,生成一致的面孔、发型甚至跨风格和场景的服装图像。\\\"cref\\\"简直可以说是换装不换脸,类似于换脸插件。而且原图面部可以是多角度,与

    2024年04月17日
    浏览(28)
  • 国内免费ChatGPT+AI绘画创作网站工具+支持GPT-4+Midjourney绘画

    GPT4.0 相信对大家应该不感到陌生吧?简单来说,GPT-4技术比之前的GPT-3.5相对来说更加智能,会根据用户的要求生成多种内容甚至也可以和用户进行创作交流。 然而,GPT-4对普通用户来说都是需要额外付费才可以使用。所以今天小编就整理一个真正免费的公益GPT4网站。不是只

    2024年02月05日
    浏览(61)
  • ChatGPT、Midjourney 5大AI工具组合技,生成AI 文字、图片及影片,开启AI 创作新局面!

    AIGC 的意思是生成式人工智慧,全名为「Artificial Intelligence Generated Content」,是透过机器学习、自然语言处理和大数据等技术,让电脑自动产生出符合人类需求的文字、图片、影音等,并能够根据不同的需求进行客制化。 AIGC 可以应用于多种产业领域,如网络营销、影视作品、

    2024年04月26日
    浏览(28)
  • 最新ChatGPT4.0工具使用教程:GPTs使用,Midjourney绘画,AI换脸,Suno-AI音乐生成大模型一站式系统使用教程

    ChatGPT3.5、GPT4.0、相信对大家应该不感到陌生吧?简单来说,GPT-4技术比之前的GPT-3.5相对来说更加智能,会根据用户的要求生成多种内容甚至也可以和用户进行创作交流。 然而,GPT-4对普通用户来说都是需要额外付费才可以使用。所以今天小编就整理一个真正可免费的AI工具,

    2024年04月14日
    浏览(39)
  • 分享6款AI绘画工具,能出图质量图片,值得使用

    之前用过很多的AI绘画工具,最近都网址丢失或是停用维护中,好多都用不了,不过好在还有一些“幸存下来”,并非全部免费,但是绘画的效果还是很不错的,出图的速度也比较快,大家感兴趣的话可以去试试! 这款电脑软件的功能可以说是非常丰富了!不仅支持文字识别

    2024年01月18日
    浏览(42)
  • Midjourney小白上手教程,3分钟学会AI绘画!

    2023年可以成为“AI元年”,随着人工智能飞跃发展,各行各业开始拥抱AI,其中设计、传媒、游戏行业与AI最好的结合方式便是AI绘画,以Midjourney为代表的AI绘画不仅能提升设计者的工作效率,还间接降低了设计师的技能门槛,因此在未来与设计相关的任何工作,最需要的,也

    2024年02月20日
    浏览(32)
  • AI根据文本语义实现AI绘画出图

    当谈到人工智能(AI)和艺术的结合时,我们经常会想到生成对抗网络(GANs)和图像生成。然而,很少有人了解到AI也可以通过文本语义生成绘画作品。在本文中,我将详细介绍如何使用深度学习和自然语言处理技术,使AI能够根据给定的文本语义生成绘画作品。 首先,我们

    2024年03月26日
    浏览(33)
  • 用ChatGPT+Midjourney 5分钟生成30条爆款小红书图文(内有详细教程)

    本期是赤辰第35期AI项目教程,文章底部准备了粉丝福利,看完后可免费领取! 今天给大家讲一下如何5分钟生成30条爆款小红书图文 先说个账号,这个应该有同学也看过,前几个月在小红书有个涨粉很快的AI绘画项目,就是分享猫咪时尚走秀就能轻松获得1W+的点赞,三个月就

    2024年02月03日
    浏览(29)
  • AI绘图实战(三):手绘出图机甲狂暴男 | Stable Diffusion成为设计师生产力工具

    S:你安装stable diffusion就是为了看小姐姐么? I :当然不是,当然是为了公司的发展谋出路~~ 预先学习 : 安装及其问题解决参考:《Windows安装Stable Diffusion WebUI及问题解决记录》; 运行使用时问题《Windows使用Stable Diffusion时遇到的各种问题整理》; 模型运用及参数《Stable D

    2024年02月10日
    浏览(33)
  • 【元壤教育AI提示工程】Midjourney神器助力,设计小白3分钟轻松打造炫酷海报!

    前言 关注「元壤教育」公众号,系统学习更多AIGC课程。 看完这篇实操教程,设计师该领盒饭了,哈哈,开个玩笑,各位老板看着办。 本教程针对完全没有设计基础的老板们,手把手教你3分钟利用Midjourney轻松打造炫酷海报。 这里有两种方法,不过本教程我们先讲解第二种。

    2024年02月12日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包