|
1 | 1 | # -*- coding: utf-8 -*- |
2 | | -import time, os |
| 2 | +import os |
| 3 | +import tempfile |
| 4 | + |
3 | 5 | from AppKit import NSPasteboard, NSPasteboardTypePNG, NSPasteboardTypeTIFF, NSPasteboardTypeString |
4 | 6 |
|
5 | 7 | def get_paste_img_file(): |
| 8 | + ''' get a img file from clipboard; |
| 9 | + the return object is a `tempfile.NamedTemporaryFile` |
| 10 | + you can use the name field to access the file path. |
| 11 | + the tmp file will be delete as soon as possible(when gc happened or close explicitly) |
| 12 | + you can not just return a path, must hold the reference''' |
| 13 | + |
6 | 14 | pb = NSPasteboard.generalPasteboard() |
7 | 15 | data_type = pb.types() |
8 | 16 | # if img file |
9 | | - print data_type |
10 | | - now = int(time.time() * 1000) # used for filename |
11 | | - if NSPasteboardTypePNG in data_type: |
12 | | - # png |
| 17 | + # print data_type |
| 18 | + # always generate png format img |
| 19 | + png_file = tempfile.NamedTemporaryFile(suffix="png") |
| 20 | + |
| 21 | + supported_image_format = (NSPasteboardTypePNG, NSPasteboardTypeTIFF) |
| 22 | + if any(filter(lambda f: f in data_type, supported_image_format)): |
| 23 | + # do not care which format it is, we convert it to png finally |
| 24 | + # system screen shotcut is png, QQ is tiff |
| 25 | + tmp_img_file = tempfile.NamedTemporaryFile() |
13 | 26 | data = pb.dataForType_(NSPasteboardTypePNG) |
14 | | - filename = '%s.png' % now |
15 | | - filepath = '/tmp/%s' % filename |
16 | | - ret = data.writeToFile_atomically_(filepath, False) |
17 | | - if ret: |
18 | | - return filepath |
19 | | - elif NSPasteboardTypeTIFF in data_type: |
20 | | - # tiff |
21 | | - data = pb.dataForType_(NSPasteboardTypeTIFF) |
22 | | - filename = '%s.tiff' % now |
23 | | - filepath = '/tmp/%s' % filename |
24 | | - ret = data.writeToFile_atomically_(filepath, False) |
25 | | - if ret: |
26 | | - os.system('sips -s format tiff /tmp/%s.tiff --out /tmp/%s.png' % (now, now)) |
27 | | - return '/tmp/%s.png' % now |
| 27 | + ret = data.writeToFile_atomically_(tmp_img_file.name, False) |
| 28 | + if not ret: return |
| 29 | + |
| 30 | + # convert it to png file |
| 31 | + os.system('sips -s format png %s --out %s' % (tmp_img_file.name, png_file.name)) |
| 32 | + |
| 33 | + # close the file explicitly |
| 34 | + tmp_img_file.close() |
| 35 | + return png_file |
| 36 | + |
28 | 37 | elif NSPasteboardTypeString in data_type: |
29 | 38 | # string todo, recognise url of png & jpg |
30 | 39 | pass |
31 | 40 |
|
| 41 | +if __name__ == '__main__': |
| 42 | + get_paste_img_file() |
32 | 43 |
|
33 | 44 |
|
34 | 45 |
|
|
0 commit comments