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
import os.path
import mimetypes
import filetype
from PIL import Image
from django.conf import settings
def get_file_type(filepath, ft=None):
ft = filetype.guess(filepath)
ext = ft.extension
return ext if ext else 'txt'
def get_filename(name):
h = hash(name)
if h < 0:
h = -h
return "{}".format(h)
def tailor_image(image_path, points, base_path='.'):
"""以左上角为原点 向右建立x轴 向下建立y轴, 同时截取多张
:param image: Image obj
:param point: [(x, y, delta_x, delta_y)]
:return:
"""
image = Image.open(image_path)
heiget = image.height
width = image.width
images = []
for idx, point in enumerate(points):
if not (width >= point[0] and width >= point[0] + point[2]) or \
not (heiget >= point[1] and heiget >= point[1] + point[3]):
continue
border = (point[0], point[1], point[0] + point[2], point[1] + point[3])
choice_image = image.crop(border)
filename = "{}_{}.{}".format(get_filename(image_path), idx, get_file_type(image_path))
base_dir = os.path.join(settings.DOWNLOAD_IMAGE_PATH)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
file_path = os.path.join(base_dir, filename)
print(file_path)
choice_image.save(file_path)
images.append(file_path)
return images