-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathimagemanipulation.py
668 lines (526 loc) · 24.7 KB
/
imagemanipulation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# import.standard
import math
import os
from io import BytesIO
from random import choice
from typing import Any, List, Optional, Union
# import.thirdparty
import discord
from discord.ext import commands
from PIL import Image, ImageDraw, ImageFont, ImageOps
# import.local
from extra import utils
class ImageManipulation(commands.Cog):
""" Categories for image manipulations and visualization. """
def __init__(self, client: commands.Bot) -> None:
""" Class' init method. """
self.client = client
self.cached_image: Union[
discord.Member.display_avatar, discord.User.display_avatar,
discord.Guild.banner] = None
@commands.Cog.listener()
async def on_ready(self) -> None:
""" Tells when the cog is ready to go. """
print('ImageManipulation cog is ready!')
@commands.command(aliases=['av', 'pfp', 'pic', 'picture', 'profile_picture'])
async def avatar(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Shows the user avatar picture.
:param member: The member to show. [Optional][Default = You]. """
if not member:
member = ctx.author
avatar = member.avatar if member.avatar else member.display_avatar
display = member.display_avatar
embed = discord.Embed(
description=f"[Default]({avatar}) - [Server]({display})",
color=int('36393F', 16)
)
embed.set_image(url=display)
self.cached_image = display
await ctx.reply(embed=embed)
@commands.command()
async def banner(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Shows the user banner picture if they have one
:param member: The member to show. [Optional][Default = You]. """
if not member:
member = ctx.author
user = await self.client.fetch_user(member.id)
banner = user.banner
if not (banner := user.banner):
if member == ctx.author:
return await ctx.reply(f"**You don't have a banner!**")
else:
return await ctx.reply(f"**{member.mention} doesn't have a banner!**")
embed = discord.Embed(
description=f"[Banner]({banner})",
color=int('36393F', 16)
)
embed.set_image(url=banner)
self.cached_image = banner
await ctx.send(embed=embed)
@commands.command(aliases=["cache", "cached_image", "ci"])
async def cached(self, ctx) -> None:
""" Shows the cached image. """
file = self.cached_image
if not file:
return await ctx.reply(f"**There isn't a cached image, {ctx.author.mention}!**")
embed = discord.Embed(
color=int('36393F', 16)
)
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
embed.set_image(url='attachment://cached_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'cached_image.png'))
@commands.command()
async def flip(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Flips an image upside down.
:param member: The member to flip the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
image = ImageOps.flip(image)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://flipped_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'flipped_image.png'))
@commands.command(aliases=["side"])
async def sideways(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Flips an image sideways.
:param member: The member to flip the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
image = ImageOps.mirror(image)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://mirrored_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'mirrored_image.png'))
@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def rain(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Rains on an image, making its colors look different.
:param member: The member of whom to rain on the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
image: Image.Image = ImageOps.posterize(image, 2)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://rain_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'rain_image.png'))
@commands.command()
@utils.not_ready()
async def explode(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Explodes an image.
:param member: The member to explode the profile picture. [Optional][Default = Cached Image] """
pass
@commands.command()
@utils.not_ready()
async def implode(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Implodes an image.
:param member: The member to implode the profile picture. [Optional][Default = Cached Image] """
pass
@commands.command()
async def rotate(self, ctx, member: Optional[discord.Member] = None, scale: Optional[int] = None) -> None:
""" Rotates an image.
:param member: The member to rotate the profile picture from. [Optional][Default = Cached Image]
:param scale: The scale to rotate the image. [Optional][Default = Random] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
if not scale:
scale = choice([90, 180, 50, 45, 270, 120, 80])
image = image.rotate(int(scale))
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://rotated_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'rotated_image.png'))
@commands.command(aliases=['light', 'brighten', 'bright'])
@commands.cooldown(1, 5, commands.BucketType.user)
async def lighten(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Lightens an image.
:param member: The member of whom to lighten the picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='lighten', percentage=percentage)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://lightened_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'lightened_image.png'))
@commands.command(aliases=['dark', 'dim'])
@commands.cooldown(1, 5, commands.BucketType.user)
async def darken(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Darkens an image.
:param member: The member of whom to darken the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='darken', percentage=percentage)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://darkened_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'darkened_image.png'))
async def image_to_byte_array(self, image: Image.Image) -> bytes:
""" Converts an image to bytes.
:param image: The image to convert to bytes. """
imgByteArr = BytesIO()
image.save(imgByteArr, format='png')
imgByteArr = imgByteArr.getvalue()
return imgByteArr
async def change_image_brightness(self, file: Any, action: str, percentage: int,
r: bool = True, g: bool = True, b: bool = True) -> None:
""" Changes the brightness level of each pixel of the image.
:param file: The file to execute the task on.
:param action: Whether to lighten or darken the image.
:param percentage: The percentage to ligthen or darken the image. """
if not isinstance(file, Image.Image):
original_image = Image.open(BytesIO(await file.read()))
else:
original_image = file
pixels = original_image.getdata()
#initialise the new image
new_image = Image.new('RGB', original_image.size)
new_image_list = []
brightness_multiplier = 1.0
if action == 'lighten':
brightness_multiplier += (percentage/100)
else:
brightness_multiplier -= (percentage/100)
# Fixes non tuple pixel sets
if isinstance(pixels[0], int):
pixels = [(px, px, px, px) for px in pixels]
#for each pixel, append the brightened or darkened version to the new image list
for pixel in pixels:
new_pixel = (
int(pixel[0] * brightness_multiplier) if r else int(pixel[0]),
int(pixel[1] * brightness_multiplier) if g else int(pixel[1]),
int(pixel[2] * brightness_multiplier) if b else int(pixel[2])
)
#check the new pixel values are within rgb range
for pixel in new_pixel:
if pixel > 255:
pixel = 255
elif pixel < 0:
pixel = 0
new_image_list.append(new_pixel)
#save the new image
new_image.putdata(new_image_list)
return new_image
@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def red(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Makes an image redder.
:param member: The member of whom to increase the red values of the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='lighten', percentage=percentage, b=False, g=False)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://red_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'red_image.png'))
@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def blue(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Makes an image bluer.
:param member: The member of whom to increase the bluer values of the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='lighten', percentage=percentage, r=False, g=False)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://blue_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'blue_image.png'))
@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def yellow(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Makes an image yellower.
:param member: The member of whom to increase the yellow values of the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='lighten', percentage=percentage, b=False)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://yellow_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'yellow_image.png'))
@commands.command(aliases=['lightblue'])
@commands.cooldown(1, 5, commands.BucketType.user)
async def light_blue(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Makes an image light-bluer.
:param member: The member of whom to increase the light blue values of the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='lighten', percentage=percentage, r=False)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://light_blue_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'light_blue_image.png'))
@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def purple(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Makes an image purpleer.
:param member: The member of whom to increase the purple values of the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='lighten', percentage=percentage, g=False)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://purple_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'purple_image.png'))
@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def green(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Makes an image greener.
:param member: The member of whom to increase the green values of the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image: Image.Image = await self.change_image_brightness(file=file, action='lighten', percentage=percentage, r=False, b=False)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://green_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'green_image.png'))
@commands.command(aliases=['grey'])
@commands.cooldown(1, 5, commands.BucketType.user)
async def gray(self, ctx, member: Optional[discord.Member] = None, percentage: int = 55) -> None:
""" Makes an image grayer/greyer.
:param member: The member of whom to increase the gray/grey values of the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
image: Image.Image = ImageOps.grayscale(image)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://gray_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'gray_image.png'))
@commands.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def wave(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Waves an image.
:param member: The member to wave the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
class WaveDeformer:
def transform(self, x, y):
y = y + 10*math.sin(x/20)
return x, y
def transform_rectangle(self, x0, y0, x1, y1):
return (*self.transform(x0, y0),
*self.transform(x0, y1),
*self.transform(x1, y1),
*self.transform(x1, y0),
)
def getmesh(self, img):
self.w, self.h = img.size
gridspace = 20
target_grid = []
for x in range(0, self.w, gridspace):
for y in range(0, self.h, gridspace):
target_grid.append((x, y, x + gridspace, y + gridspace))
source_grid = [self.transform_rectangle(*rect) for rect in target_grid]
return [t for t in zip(target_grid, source_grid)]
wave_image = ImageOps.deform(image, WaveDeformer())
self.cached_image = wave_image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://wave_image.png')
bytes_image = await self.image_to_byte_array(wave_image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'wave_image.png'))
@commands.command(aliases=["negative", "negate"])
async def invert(self, ctx, member: Optional[discord.Member] = None) -> None:
""" Inverts an image to its negative form..
:param member: The member to invert the profile picture. [Optional][Default = Cached Image] """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
if isinstance(image, Image.Image):
image = image.convert('RGB')
image = ImageOps.invert(image)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://inverted_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'inverted_image.png'))
async def get_font(self, image: Image.Image, text: str, font_name: str = None) -> ImageFont:
""" Gets the font sized proportionally to the image size.
:param image: The image to proportion the font to.
:param text: The base text. """
fontsize = 1 # starting font size
if not font_name:
font_name = 'built titling sb.ttf'
font_path: str = f'media/fonts/{font_name}'
# Portion of image width you want text width to be
img_fraction = 0.50
font = ImageFont.truetype(font_path, fontsize)
while font.getsize(text)[0] < img_fraction*image.size[0]:
# Iterates until the text size is just larger than the criteria
fontsize += 1
font = ImageFont.truetype(font_path, fontsize)
# Optionally de-increments to be sure it is less than criteria
fontsize -= 1
font = ImageFont.truetype(font_path, fontsize)
return font
@commands.command(aliases=['write', 'cap'])
@commands.cooldown(1, 5, commands.BucketType.user)
async def caption(self, ctx, member: Optional[discord.Member] = None, *, text: str = None) -> None:
""" Puts a caption on an image.
:param member: The member to put the caption on the profile picture. [Optional][Default = Cached Image].
:param text: The caption text to put on the image. """
file: Any = None
if member:
file = member.display_avatar
else:
if self.cached_image:
file = self.cached_image
else:
file = ctx.author.display_avatar
if not text:
return await ctx.reply("**Please, inform a `caption text`!**")
image = file if isinstance(file, Image.Image) else Image.open(BytesIO(await file.read()))
text = str(text).strip() if text else None
# Puts the caption
font = await self.get_font(image, text)
W, H = image.size
draw = ImageDraw.Draw(image)
w, h = draw.textsize(text, font=font)
draw.text(((W-w)/2,(H-h)/2), text, fill="white", font=font)
# draw.text(((W-w)/2,(H-h)/2-120), text, fill="white", font=small)
self.cached_image = image
embed = discord.Embed(
color=int('36393F', 16)
)
embed.set_image(url='attachment://captioned_image.png')
bytes_image = await self.image_to_byte_array(image)
await ctx.reply(embed=embed, file=discord.File(BytesIO(bytes_image), 'captioned_image.png'))
def setup(client: commands.Cog) -> None:
""" Cog's setup function. """
client.add_cog(ImageManipulation(client))