def picture_type(octets):
pict_type = imghdr.what(None, octets)
if pict_type is None:
if (octets.startswith(b'<') and
b'<svg' in octets[:200] and
octets.rstrip().endswith(b'</svg>')):
pict_type = 'svg'
return pict_type
python类what()的实例源码
def uploaded_images_json(request, upload_path=None):
upload_path = upload_path or UPLOAD_PATH
results = list()
path = os.path.join(settings.MEDIA_ROOT, upload_path)
if os.path.isdir(path):
for image in os.listdir(path):
image_path = '{0}{1}'.format(path, smart_str(image))
if not os.path.isdir(image_path) and imghdr.what(image_path):
thumb = get_thumbnail(image_path, '100x74', crop='center')
image_url = os.path.join(settings.MEDIA_URL, upload_path, image)
results.append({'thumb': thumb.url, 'image': image_url})
return HttpResponse(json.dumps(results))
return HttpResponse('{}')
def valid_image_file_odl(file_obj):
res = imghdr.what('ignored.txt', h=file_obj.read())
return res in ALLOWED_EXTENSIONS
def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
self.set_payload(_imagedata)
_encoder(self)
def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
self.set_payload(_imagedata)
_encoder(self)
def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
self.set_payload(_imagedata)
_encoder(self)
def test_generate(self):
fd, outfile = tempfile.mkstemp(suffix='.png')
# convert CT cube to DICOM
pytrip.utils.rst_plot.main([self.rst_file, outfile])
# check if destination file is not empty
self.assertTrue(os.path.exists(outfile))
self.assertGreater(os.path.getsize(outfile), 0)
self.assertEqual(imghdr.what(outfile), 'png')
os.close(fd) # Windows needs it
os.remove(outfile) # we need only temp filename, not the file
def test_relative_dos_plot(self):
working_dir = tempfile.mkdtemp() # make temp working dir for output file
output_file = os.path.join(working_dir, "foo.png")
pytrip.utils.dvhplot.main(args=[self.dos, self.vdx, 'target', '-l', '-v', '-o', output_file])
logger.info("Checking if " + output_file + " is PNG")
self.assertEqual(imghdr.what(output_file), 'png')
logger.info("Removing " + working_dir)
shutil.rmtree(working_dir)
def test_absolute_dos_plot(self):
working_dir = tempfile.mkdtemp() # make temp working dir for output file
output_file = os.path.join(working_dir, "foo.png")
pytrip.utils.dvhplot.main(args=[self.dos, self.vdx, 'target', '-l', '-v', '-d 2.0', '-o', output_file])
logger.info("Checking if " + output_file + " is PNG")
self.assertEqual(imghdr.what(output_file), 'png')
logger.info("Removing " + working_dir)
shutil.rmtree(working_dir)
def test_let_plot(self):
working_dir = tempfile.mkdtemp() # make temp working dir for output file
output_file = os.path.join(working_dir, "foo.png")
pytrip.utils.dvhplot.main(args=[self.let, self.vdx, 'target', '-l', '-v', '-o', output_file])
logger.info("Checking if " + output_file + " is PNG")
self.assertEqual(imghdr.what(output_file), 'png')
logger.info("Removing " + working_dir)
shutil.rmtree(working_dir)
def test_convert_all(self):
working_dir = tempfile.mkdtemp() # make temp working dir for converter output files
pytrip.utils.cubeslice.main(args=['--data', self.dos, '--ct', self.ctx, '-o', working_dir])
output_file_list = glob.glob(os.path.join(working_dir, "*.png"))
logger.info("Checking if number of output files is sufficient")
self.assertEqual(len(output_file_list), 300)
for output_file in output_file_list:
logger.info("Checking if " + output_file + " is PNG")
self.assertEqual(imghdr.what(output_file), 'png')
logger.info("Removing " + working_dir)
shutil.rmtree(working_dir)
def getImageSize(fname):
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
raise RuntimeError("Invalid Header")
if imghdr.what(fname) == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
raise RuntimeError("PNG: Invalid check")
width, height = struct.unpack('>ii', head[16:24])
elif imghdr.what(fname) == 'gif':
width, height = struct.unpack('<HH', head[6:10])
elif imghdr.what(fname) == 'jpeg':
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
else:
raise RuntimeError("Unsupported format")
return width, height
def getImageSize(fname):
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
raise RuntimeError("Invalid Header")
if imghdr.what(fname) == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
raise RuntimeError("PNG: Invalid check")
width, height = struct.unpack('>ii', head[16:24])
elif imghdr.what(fname) == 'gif':
width, height = struct.unpack('<HH', head[6:10])
elif imghdr.what(fname) == 'jpeg':
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
else:
raise RuntimeError("Unsupported format")
return width, height
def process_request(self, path, query_string, content):
payload = json.loads(content)
path = path.split("/")
conversation_id = path[1]
if not conversation_id:
raise ValueError("conversation id must be provided in path")
text = None
if "echo" in payload:
text = payload["echo"]
image_data = None
image_filename = None
if "image" in payload:
if "base64encoded" in payload["image"]:
image_raw = base64.b64decode(payload["image"]["base64encoded"])
image_data = io.BytesIO(image_raw)
if "filename" in payload["image"]:
image_filename = payload["image"]["filename"]
else:
image_type = imghdr.what('ignore', image_raw)
image_filename = str(int(time.time())) + "." + image_type
logger.info("automatic image filename: {}".format(image_filename))
if not text and not image_data:
raise ValueError("nothing to send")
results = await self.send_data(conversation_id, text, image_data=image_data, image_filename=image_filename)
return results
def process_payload(self, path, query_string, payload):
logging.warning("[DEPRECATED] simpledemo.webhookReceiver, use sinks.generic.SimpleMessagePoster")
sinkname = self.sinkname
path = path.split("/")
conversation_id = path[1]
if conversation_id is None:
print("{}: conversation id must be provided as part of path".format(sinkname))
return
image_id = None
if "image" in payload:
image_data = False
image_filename = False
image_type = 'unknown'
if "base64encoded" in payload["image"]:
raw = base64.b64decode(payload["image"]["base64encoded"], None, True)
image_data = io.BytesIO(raw)
image_type = imghdr.what('ignore', raw)
if not image_type:
image_type = 'error'
if "filename" in payload["image"]:
image_filename = payload["image"]["filename"]
else:
image_filename = str(int(time.time())) + "." + image_type
print("{}: uploading image: {}".format(sinkname, image_filename))
image_id = await webhookReceiver._bot._client.upload_image(image_data, filename=image_filename)
html = ""
if "echo" in payload:
html = payload["echo"]
else:
# placeholder text
html = "<b>hello world</b>"
segments = simple_parse_to_segments(html)
print("{} sending segments: {}".format(sinkname, len(segments)))
await self._bot.coro_send_message(conversation_id, segments, context=None, image_id=image_id)
def getImageSize(fname):
with open(fname, 'rb') as fhandle:
head = fhandle.read(24)
if len(head) != 24:
raise RuntimeError("Invalid Header")
if imghdr.what(fname) == 'png':
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
raise RuntimeError("PNG: Invalid check")
width, height = struct.unpack('>ii', head[16:24])
elif imghdr.what(fname) == 'gif':
width, height = struct.unpack('<HH', head[6:10])
elif imghdr.what(fname) == 'jpeg':
fhandle.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
fhandle.seek(size, 1)
byte = fhandle.read(1)
while ord(byte) == 0xff:
byte = fhandle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', fhandle.read(2))[0] - 2
# We are at a SOFn block
fhandle.seek(1, 1) # Skip `precision' byte.
height, width = struct.unpack('>HH', fhandle.read(4))
else:
raise RuntimeError("Unsupported format")
return width, height
def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, **_params):
"""Create an image/* type MIME document.
_imagedata is a string containing the raw image data. If this data
can be decoded by the standard Python `imghdr' module, then the
subtype will be automatically included in the Content-Type header.
Otherwise, you can specify the specific image subtype via the _subtype
parameter.
_encoder is a function which will perform the actual encoding for
transport of the image data. It takes one argument, which is this
Image instance. It should use get_payload() and set_payload() to
change the payload to the encoded form. It should also add any
Content-Transfer-Encoding or other headers to the message as
necessary. The default encoding is Base64.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
_subtype = imghdr.what(None, _imagedata)
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, **_params)
self.set_payload(_imagedata)
_encoder(self)
def __call__(self, form, field):
if field.data is None or imghdr.what('unused', field.data.read()) is None:
message = self.message or 'An image file is required'
raise StopValidation(message)
field.data.seek(0)
def picon_post_processing(self, piconfilepath):
"""Check type of image received and convert to png
if necessary
"""
ext = ""
# get image type
try:
ext = imghdr.what(piconfilepath)
except Exception, e:
if DEBUG:
print(e)
return
# if image but not png convert to png
if (ext is not None) and (ext is not 'png'):
if DEBUG:
print('Converting Picon to png')
try:
Image.open(piconfilepath).save("{}.{}".format(piconfilepath, 'png'))
except Exception, e:
if DEBUG:
print(e)
return
try:
# remove non png file
os.remove(piconfilepath)
except Exception, e:
if DEBUG:
print(e)
return
else:
# rename to correct extension
try:
os.rename(piconfilepath, "{}.{}".format(piconfilepath, ext))
except Exception, e:
if DEBUG:
print(e)
pass
def set_cover(self, data):
"""Set the cover image to the given data."""
self._cover = 'cover.' + imghdr.what(None, h=data)
with open(str(self.path / 'EPUB/covers' / self._cover), 'wb') as file:
file.write(data)
self._write('cover.xhtml', 'EPUB/cover.xhtml', cover=self._cover)