Advertisement
NaroxEG

Emojify

Apr 18th, 2024
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3. from dotenv import load_dotenv
  4. import os
  5. from PIL import Image
  6. from io import BytesIO
  7.  
  8. load_dotenv()
  9. TOKEN = os.environ.get("TOKEN")
  10.  
  11. client = commands.Bot(command_prefix="!", intents=discord.Intents.default())
  12. tree = client.tree
  13.  
  14. @client.event
  15. async def on_ready():
  16.     print(f"Logged in as {client.user}")
  17.     synced = await tree.sync()
  18.     print(f"Synced {len(synced)} Command(s).")
  19.  
  20. new_size = 32
  21.  
  22. COLORS = {
  23.     (49, 55, 61):    "⬛",
  24.     (85, 172, 238):  "🟦",
  25.     (221, 46, 68):   "🟥",
  26.     (253, 203, 88):  "🟨",
  27.     (193, 105, 79):  "🟫",
  28.     (244, 144, 12):  "🟧",
  29.     (170, 142, 214): "🟪",
  30.     (230, 231, 232): "⬜",
  31.     (120, 177, 89):  "🟩",
  32. }
  33.  
  34.  
  35. @tree.command(name="emojify", description="converts image into emojis of pixels")
  36. async def _emojify(interaction: discord.Interaction, image: discord.Attachment):
  37.     await interaction.response.defer()
  38.  
  39.     with BytesIO(await image.read()) as file:
  40.         resized = Image.open(file).resize((new_size, new_size), resample=Image.NEAREST).convert("RGB")    
  41.     msg = convertPixels(resized)
  42.  
  43.     await interaction.followup.send(f"```{msg}```")
  44.  
  45.  
  46. def convertPixels(img: Image.Image):
  47.     pixelsArray = img.load()
  48.     emojified = ""
  49.    
  50.     width, height = img.size
  51.  
  52.     for row in range(height):
  53.         for column in range(width):
  54.             nearestColor = getNearestColor(pixelsArray[column, row])
  55.             emojified += nearestColor            
  56.         emojified += '\n'
  57.     return emojified
  58.  
  59. def getNearestColor(pixels: tuple):
  60.     distancesList = []
  61.  
  62.     for refPixels, color in COLORS.items():
  63.         r1, g1, b1 = refPixels
  64.         r2, g2, b2 = pixels
  65.         distance = ((r2-r1)**2 + (g2-g1)**2 + (b2-b1)**2) ** 0.5
  66.        
  67.         distancesList.append(distance)
  68.  
  69.     sortedList = sorted(distancesList)
  70.     idx = distancesList.index(sortedList[0])
  71.  
  72.     return list(COLORS.values())[idx]
  73.  
  74. client.run(TOKEN)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement