当前位置:   article > 正文

Comfyui api图生图_comfyui 上传图片

comfyui 上传图片

一、comfyui添加图片上传节点

需要两个文件,

允许上传base64格式的图片和url格式的图片


 

init.py

  1. from .image_load import LoadImageFromURLOrBase64, LoadMaskFromURLOrBase64
  2. NODE_CLASS_MAPPINGS = {"Load Image From URL/Base64": LoadImageFromURLOrBase64,
  3. "Load Mask From URL/Base64": LoadMaskFromURLOrBase64,
  4. #"Save Image As Base64": SaveImageBase64,
  5. #"Save Temp Image As Jpeg": SaveTempImageJpeg
  6. }
  7. __all__ = ['NODE_CLASS_MAPPINGS']

image_loag.py

  1. import base64
  2. import random
  3. import numpy as np
  4. import torch
  5. import requests
  6. import json
  7. import folder_paths
  8. import os
  9. # import piexif
  10. from PIL import Image, JpegImagePlugin, ImageOps
  11. from io import BytesIO
  12. class LoadImageFromURLOrBase64:
  13. @classmethod
  14. def INPUT_TYPES(s):
  15. return {"required": {
  16. "image": ("STRING",{"default": "https://aiiiinimg.oss-cn-shenzhen.aliyuncs.com/AiImages/2024-03-29/1e6d03aa68b34612961d8e0b695c94bd.jpeg"}),
  17. }}
  18. CATEGORY = "image"
  19. RETURN_TYPES = ("IMAGE",)
  20. FUNCTION = "load_image"
  21. def load_image(self, image):
  22. if image.startswith(('http://', 'https://')):
  23. response = requests.get(image)
  24. img = Image.open(BytesIO(response.content))
  25. elif image.startswith('data:image/'):
  26. _, base64_str = image.split(',', 1)
  27. img = Image.open(BytesIO(base64.b64decode(base64_str)))
  28. else:
  29. img = Image.open(BytesIO(base64.b64decode(image)))
  30. img = ImageOps.exif_transpose(img)
  31. if img.mode == 'I':
  32. img = img.point(lambda i: i * (1 / 255))
  33. img = img.convert("RGB")
  34. image = np.array(img).astype(np.float32) / 255.0
  35. image_tensor = torch.from_numpy(image)[None,]
  36. return (image_tensor,)
  37. class LoadMaskFromURLOrBase64:
  38. @classmethod
  39. def INPUT_TYPES(s):
  40. return {"required": {
  41. "image": ("STRING",{"default": "https://aiiiinimg.oss-cn-shenzhen.aliyuncs.com/AiImages/2024-03-29/1e6d03aa68b34612961d8e0b695c94bd.jpeg"}),
  42. }}
  43. CATEGORY = "mask"
  44. RETURN_TYPES = ("MASK",)
  45. FUNCTION = "load_mask"
  46. def load_mask(self, image):
  47. if image.startswith(('http://', 'https://')):
  48. response = requests.get(image)
  49. img = Image.open(BytesIO(response.content))
  50. elif image.startswith('data:image/'):
  51. _, base64_str = image.split(',', 1)
  52. img = Image.open(BytesIO(base64.b64decode(base64_str)))
  53. else:
  54. img = Image.open(BytesIO(base64.b64decode(image)))
  55. img = img.convert("L")
  56. mask = np.array(img).astype(np.float32)
  57. mask = np.where(mask > 127, 1, 0).astype(np.float32)
  58. mask_tensor = torch.from_numpy(mask)[None, None, ]
  59. return (mask_tensor,)

二、重启comfyui

三、修改api.py router.py   index.html

api.py

  1. # 图生图
  2. class ImgToImgModel(BaseModel):
  3. image: str
  4. prompt: str
  5. @app.post("/imgGenerateImg", tags=["perfume bottle"])
  6. async def imgGenerateImg(data:ImgToImgModel):
  7. return await process_imggenerateimg(data)
  8. # 将 static 目录中的文件作为静态文件提供
  9. app.mount("/static", StaticFiles(directory="demo/static"), name="static")

router.py

  1. async def process_imggenerateimg(data):
  2. client_id = str(uuid.uuid4())
  3. prompt = load_json_template('demo/jsonFile/img2img_api.json')
  4. prompt["3"]["inputs"]["seed"] = random.randrange(10**14, 10**15)
  5. prompt["6"]["inputs"]["text"] = data.prompt
  6. prompt["12"]["inputs"]["image"] = data.image
  7. images =await get_outputs(client_id,prompt)
  8. return images

index.html

  1. <h1>Upload Image and Enter Keyword</h1>
  2. <input type="file" id="imageInput" accept="image/*"><br><br>
  3. <input type="text" id="keywordInput" placeholder="Enter keyword"><br><br>
  4. <button id="submitButton" onclick="handleSubmit()">Submit</button>
  5. <div id="uploadedImageContainer">
  6. <h3>Uploaded Image:</h3>
  7. <img id="uploadedImage" src="" alt="Uploaded Image">
  8. </div>
  9. <div id="returnedImageContainer">
  10. <h3>Returned Image:</h3>
  11. <img id="returnedImage" src="" alt="Returned Image">
  12. </div>
  1. // 图生图
  2. document.getElementById('uploadedImageContainer').style.display = 'none';
  3. document.getElementById('returnedImageContainer').style.display = 'none';
  4. async function getBase64(file) {
  5. return new Promise((resolve, reject) => {
  6. const reader = new FileReader();
  7. reader.readAsDataURL(file);
  8. reader.onload = () => resolve(reader.result);
  9. // reader.onload = () => {
  10. // // Remove the data:image/jpeg;base64, part
  11. // const base64String = reader.result.replace(/^data:image\/jpeg;base64,/, '');
  12. // resolve(base64String);
  13. // };
  14. reader.onerror = error => reject(error);
  15. });
  16. }
  17. async function handleSubmit() {
  18. const imageInput = document.getElementById('imageInput');
  19. const keywordInput = document.getElementById('keywordInput');
  20. const uploadedImage = document.getElementById('uploadedImage');
  21. const returnedImage = document.getElementById('returnedImage');
  22. const uploadedImageContainer = document.getElementById('uploadedImageContainer');
  23. const returnedImageContainer = document.getElementById('returnedImageContainer');
  24. if (!imageInput.files.length || !keywordInput.value) {
  25. alert('Please upload an image and enter a keyword.');
  26. return;
  27. }
  28. const file = imageInput.files[0];
  29. const base64Image = await getBase64(file);
  30. // console.log(file)
  31. // console.log(base64Image)
  32. uploadedImage.src = base64Image;
  33. // uploadedImage.src = `data:image/jpeg;base64,${base64Image}`;
  34. uploadedImageContainer.style.display = 'block';
  35. const requestData = {
  36. image: base64Image,
  37. prompt: keywordInput.value
  38. };
  39. try {
  40. const response = await fetch('/imgGenerateImg', {
  41. method: 'POST',
  42. headers: {
  43. 'Content-Type': 'application/json'
  44. },
  45. body: JSON.stringify(requestData)
  46. });
  47. if (response.ok) {
  48. const data = await response.json();
  49. console.log(response)
  50. console.log(data)
  51. // that.image1 = "data:image/png;base64,"+response.data.images;
  52. returnedImage.src = "data:image/png;base64,"+data.images[0];
  53. returnedImageContainer.style.display = 'block';
  54. } else {
  55. console.error('Error:', response.statusText);
  56. }
  57. } catch (error) {
  58. console.error('Error:', error);
  59. }
  60. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/944803
推荐阅读
相关标签
  

闽ICP备14008679号