1、安装第三方库。
1
|
pip install pillow
|
2、函数示例。
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
|
#encoding: utf-8
#author: walker
#date: 2016-07-26
#summary: 判断图片的有效性
import
io
import
imghdr
from
os
import
PathLike
from
PIL
import
Image
#判断文件是否为有效(完整)的图片
#输入参数为文件路径,或文件对象
def
IsValidImage(
file
):
bValid
=
True
if
isinstance
(
file
, (
str
, PathLike)):
fileObj
=
open
(
file
,
'rb'
)
else
:
fileObj
=
file
buf
=
fileObj.read()
if
buf[
6
:
10
]
in
(b
'JFIF'
, b
'Exif'
):
#jpg图片
if
not
buf.rstrip(b
'\0\r\n'
).endswith(b
'\xff\xd9'
):
bValid
=
False
else
:
try
:
Image.
open
(fileObj).verify()
except
:
bValid
=
False
return
bValid
#判断文件是否为有效(完整)的图片
#输入参数为bytes,如网络请求返回的二进制数据
def
IsValidImage4Bytes(buf):
bValid
=
True
try
:
Image.
open
(io.BytesIO(buf)).verify()
except
:
bValid
=
False
return
bValid
#判断文件是否为有效(完整)的图片
#输入参数为bytes,如网络请求返回的二进制数据
def
IsValidImage4Bytes(buf):
bValid
=
True
if
buf[
6
:
10
]
in
(b
'JFIF'
, b
'Exif'
):
#jpg图片
if
not
buf.rstrip(b
'\0\r\n'
).endswith(b
'\xff\xd9'
):
bValid
=
False
else
:
try
:
Image.
open
(io.BytesIO(buf)).verify()
except
:
bValid
=
False
return
bValid
|
相关阅读:
2、Open PIL image from byte file
4、Pillow生成gif文件大小问题:Gif image size problem
5、
*** walker ***
本文转自walker snapshot博客51CTO博客,原文链接http://blog.51cto.com/walkerqt/1830138如需转载请自行联系原作者
RQSLT