-
Notifications
You must be signed in to change notification settings - Fork 116
/
imgcpy.py
executable file
·63 lines (43 loc) · 1.58 KB
/
imgcpy.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
#!/usr/bin/env python3
import sys
import subprocess
# Copy a file, suitably downsized, to the clipboard in PNG format
# so it can be pasted by an app like Discord.
# Usage: imgcpy foo.jpg [new-pixel-width]
# From the commandline:
# convert $img png:- | xclip -selection clipboard -target image/png
# but this script also resizes if the file is large.
# To verify this worked:
# Show type available: xclip -selection clipboard -t TARGETS -o
# Get it: xclip -selection clipboard -t image/png -o > /tmp/img.png
# Images can be a little over the given size without being rescaled
SLOP = 1.3
def copy_to_clip(imgfile, maxwidth):
ident = subprocess.check_output(['identify', imgfile])
width, height = ident.split()[2].split(b'x')
args = ['convert', imgfile]
if width >= height:
if int(width) > maxwidth*SLOP:
print("Rescaling (landscape)")
args.append('-scale')
args.append('%dx' % maxwidth)
else:
if int(height) > maxwidth*SLOP:
print("Rescaling (portrait)")
args.append('-scale')
args.append('x%d' % maxwidth)
args.append('png:-')
pngbits = subprocess.check_output(args)
subprocess.run(['xclip', '-selection', 'clipboard',
'-target', 'image/png'],
input=pngbits)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: imgcpy foo.jpg [approx-max-dimension]")
sys.exit(1)
img = sys.argv[1]
if len(sys.argv) > 2:
width = int(sys.argv[2])
else:
width = 600
copy_to_clip(img, width)