def crc(self, cid, data):
"Read and verify checksum"
# Skip CRC checks for ancillary chunks if allowed to load truncated images
# 5th byte of first char is 1 [specs, section 5.4]
if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
self.crc_skip(cid, data)
return
try:
crc1 = Image.core.crc32(data, Image.core.crc32(cid))
crc2 = i16(self.fp.read(2)), i16(self.fp.read(2))
if crc1 != crc2:
raise SyntaxError("broken PNG file (bad header checksum in %s)"
% cid)
except struct.error:
raise SyntaxError("broken PNG file (incomplete checksum in %s)"
% cid)
python类LOAD_TRUNCATED_IMAGES的实例源码
def crc(self, cid, data):
"Read and verify checksum"
# Skip CRC checks for ancillary chunks if allowed to load truncated images
# 5th byte of first char is 1 [specs, section 5.4]
if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
self.crc_skip(cid, data)
return
try:
crc1 = Image.core.crc32(data, Image.core.crc32(cid))
crc2 = i16(self.fp.read(2)), i16(self.fp.read(2))
if crc1 != crc2:
raise SyntaxError("broken PNG file (bad header checksum in %s)"
% cid)
except struct.error:
raise SyntaxError("broken PNG file (incomplete checksum in %s)"
% cid)
def crc(self, cid, data):
"Read and verify checksum"
# Skip CRC checks for ancillary chunks if allowed to load truncated images
# 5th byte of first char is 1 [specs, section 5.4]
if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
self.crc_skip(cid, data)
return
try:
crc1 = Image.core.crc32(data, Image.core.crc32(cid))
crc2 = i16(self.fp.read(2)), i16(self.fp.read(2))
if crc1 != crc2:
raise SyntaxError("broken PNG file (bad header checksum in %s)"
% cid)
except struct.error:
raise SyntaxError("broken PNG file (incomplete checksum in %s)"
% cid)
def crc(self, cid, data):
"Read and verify checksum"
# Skip CRC checks for ancillary chunks if allowed to load truncated images
# 5th byte of first char is 1 [specs, section 5.4]
if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
self.crc_skip(cid, data)
return
try:
crc1 = Image.core.crc32(data, Image.core.crc32(cid))
crc2 = i16(self.fp.read(2)), i16(self.fp.read(2))
if crc1 != crc2:
raise SyntaxError("broken PNG file (bad header checksum in %s)"
% cid)
except struct.error:
raise SyntaxError("broken PNG file (incomplete checksum in %s)"
% cid)
def crc(self, cid, data):
"Read and verify checksum"
# Skip CRC checks for ancillary chunks if allowed to load truncated images
# 5th byte of first char is 1 [specs, section 5.4]
if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
self.crc_skip(cid, data)
return
try:
crc1 = Image.core.crc32(data, Image.core.crc32(cid))
crc2 = i16(self.fp.read(2)), i16(self.fp.read(2))
if crc1 != crc2:
raise SyntaxError("broken PNG file (bad header checksum in %r)"
% cid)
except struct.error:
raise SyntaxError("broken PNG file (incomplete checksum in %r)"
% cid)
def chunk_iCCP(self, pos, length):
# ICC profile
s = ImageFile._safe_read(self.fp, length)
# according to PNG spec, the iCCP chunk contains:
# Profile name 1-79 bytes (character string)
# Null separator 1 byte (null character)
# Compression method 1 byte (0)
# Compressed profile n bytes (zlib with deflate compression)
i = s.find(b"\0")
logger.debug("iCCP profile name %s", s[:i])
logger.debug("Compression method %s", i8(s[i]))
comp_method = i8(s[i])
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in iCCP chunk" %
comp_method)
try:
icc_profile = _safe_zlib_decompress(s[i+2:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
icc_profile = None
else:
raise
except zlib.error:
icc_profile = None # FIXME
self.im_info["icc_profile"] = icc_profile
return s
def chunk_zTXt(self, pos, length):
# compressed text
s = ImageFile._safe_read(self.fp, length)
try:
k, v = s.split(b"\0", 1)
except ValueError:
k = s
v = b""
if v:
comp_method = i8(v[0])
else:
comp_method = 0
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in zTXt chunk" %
comp_method)
try:
v = _safe_zlib_decompress(v[1:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
v = b""
else:
raise
except zlib.error:
v = b""
if k:
if bytes is not str:
k = k.decode('latin-1', 'strict')
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
self.check_text_memory(len(v))
return s
def chunk_iCCP(self, pos, length):
# ICC profile
s = ImageFile._safe_read(self.fp, length)
# according to PNG spec, the iCCP chunk contains:
# Profile name 1-79 bytes (character string)
# Null separator 1 byte (null character)
# Compression method 1 byte (0)
# Compressed profile n bytes (zlib with deflate compression)
i = s.find(b"\0")
logger.debug("iCCP profile name %s", s[:i])
logger.debug("Compression method %s", i8(s[i]))
comp_method = i8(s[i])
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in iCCP chunk" %
comp_method)
try:
icc_profile = _safe_zlib_decompress(s[i+2:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
icc_profile = None
else:
raise
except zlib.error:
icc_profile = None # FIXME
self.im_info["icc_profile"] = icc_profile
return s
def chunk_zTXt(self, pos, length):
# compressed text
s = ImageFile._safe_read(self.fp, length)
try:
k, v = s.split(b"\0", 1)
except ValueError:
k = s
v = b""
if v:
comp_method = i8(v[0])
else:
comp_method = 0
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in zTXt chunk" %
comp_method)
try:
v = _safe_zlib_decompress(v[1:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
v = b""
else:
raise
except zlib.error:
v = b""
if k:
if bytes is not str:
k = k.decode('latin-1', 'strict')
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
self.check_text_memory(len(v))
return s
def chunk_iCCP(self, pos, length):
# ICC profile
s = ImageFile._safe_read(self.fp, length)
# according to PNG spec, the iCCP chunk contains:
# Profile name 1-79 bytes (character string)
# Null separator 1 byte (null character)
# Compression method 1 byte (0)
# Compressed profile n bytes (zlib with deflate compression)
i = s.find(b"\0")
logger.debug("iCCP profile name %s", s[:i])
logger.debug("Compression method %s", i8(s[i]))
comp_method = i8(s[i])
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in iCCP chunk" %
comp_method)
try:
icc_profile = _safe_zlib_decompress(s[i+2:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
icc_profile = None
else:
raise
except zlib.error:
icc_profile = None # FIXME
self.im_info["icc_profile"] = icc_profile
return s
def chunk_zTXt(self, pos, length):
# compressed text
s = ImageFile._safe_read(self.fp, length)
try:
k, v = s.split(b"\0", 1)
except ValueError:
k = s
v = b""
if v:
comp_method = i8(v[0])
else:
comp_method = 0
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in zTXt chunk" %
comp_method)
try:
v = _safe_zlib_decompress(v[1:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
v = b""
else:
raise
except zlib.error:
v = b""
if k:
if bytes is not str:
k = k.decode('latin-1', 'strict')
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
self.check_text_memory(len(v))
return s
def chunk_zTXt(self, pos, length):
# compressed text
s = ImageFile._safe_read(self.fp, length)
try:
k, v = s.split(b"\0", 1)
except ValueError:
k = s
v = b""
if v:
comp_method = i8(v[0])
else:
comp_method = 0
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in zTXt chunk" %
comp_method)
try:
v = _safe_zlib_decompress(v[1:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
v = b""
else:
raise
except zlib.error:
v = b""
if k:
if bytes is not str:
k = k.decode('latin-1', 'strict')
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
self.check_text_memory(len(v))
return s
def chunk_iCCP(self, pos, length):
# ICC profile
s = ImageFile._safe_read(self.fp, length)
# according to PNG spec, the iCCP chunk contains:
# Profile name 1-79 bytes (character string)
# Null separator 1 byte (null character)
# Compression method 1 byte (0)
# Compressed profile n bytes (zlib with deflate compression)
i = s.find(b"\0")
logger.debug("iCCP profile name %r", s[:i])
logger.debug("Compression method %s", i8(s[i]))
comp_method = i8(s[i])
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in iCCP chunk" %
comp_method)
try:
icc_profile = _safe_zlib_decompress(s[i+2:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
icc_profile = None
else:
raise
except zlib.error:
icc_profile = None # FIXME
self.im_info["icc_profile"] = icc_profile
return s
def chunk_zTXt(self, pos, length):
# compressed text
s = ImageFile._safe_read(self.fp, length)
try:
k, v = s.split(b"\0", 1)
except ValueError:
k = s
v = b""
if v:
comp_method = i8(v[0])
else:
comp_method = 0
if comp_method != 0:
raise SyntaxError("Unknown compression method %s in zTXt chunk" %
comp_method)
try:
v = _safe_zlib_decompress(v[1:])
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
v = b""
else:
raise
except zlib.error:
v = b""
if k:
if bytes is not str:
k = k.decode('latin-1', 'strict')
v = v.decode('latin-1', 'replace')
self.im_info[k] = self.im_text[k] = v
self.check_text_memory(len(v))
return s
def chunk_iTXt(self, pos, length):
# international text
r = s = ImageFile._safe_read(self.fp, length)
try:
k, r = r.split(b"\0", 1)
except ValueError:
return s
if len(r) < 2:
return s
cf, cm, r = i8(r[0]), i8(r[1]), r[2:]
try:
lang, tk, v = r.split(b"\0", 2)
except ValueError:
return s
if cf != 0:
if cm == 0:
try:
v = _safe_zlib_decompress(v)
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
return s
else:
raise
except zlib.error:
return s
else:
return s
if bytes is not str:
try:
k = k.decode("latin-1", "strict")
lang = lang.decode("utf-8", "strict")
tk = tk.decode("utf-8", "strict")
v = v.decode("utf-8", "strict")
except UnicodeError:
return s
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
self.check_text_memory(len(v))
return s
# --------------------------------------------------------------------
# PNG reader
def chunk_iTXt(self, pos, length):
# international text
r = s = ImageFile._safe_read(self.fp, length)
try:
k, r = r.split(b"\0", 1)
except ValueError:
return s
if len(r) < 2:
return s
cf, cm, r = i8(r[0]), i8(r[1]), r[2:]
try:
lang, tk, v = r.split(b"\0", 2)
except ValueError:
return s
if cf != 0:
if cm == 0:
try:
v = _safe_zlib_decompress(v)
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
return s
else:
raise
except zlib.error:
return s
else:
return s
if bytes is not str:
try:
k = k.decode("latin-1", "strict")
lang = lang.decode("utf-8", "strict")
tk = tk.decode("utf-8", "strict")
v = v.decode("utf-8", "strict")
except UnicodeError:
return s
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
self.check_text_memory(len(v))
return s
# --------------------------------------------------------------------
# PNG reader
def chunk_iTXt(self, pos, length):
# international text
r = s = ImageFile._safe_read(self.fp, length)
try:
k, r = r.split(b"\0", 1)
except ValueError:
return s
if len(r) < 2:
return s
cf, cm, r = i8(r[0]), i8(r[1]), r[2:]
try:
lang, tk, v = r.split(b"\0", 2)
except ValueError:
return s
if cf != 0:
if cm == 0:
try:
v = _safe_zlib_decompress(v)
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
return s
else:
raise
except zlib.error:
return s
else:
return s
if bytes is not str:
try:
k = k.decode("latin-1", "strict")
lang = lang.decode("utf-8", "strict")
tk = tk.decode("utf-8", "strict")
v = v.decode("utf-8", "strict")
except UnicodeError:
return s
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
self.check_text_memory(len(v))
return s
# --------------------------------------------------------------------
# PNG reader
def chunk_iTXt(self, pos, length):
# international text
r = s = ImageFile._safe_read(self.fp, length)
try:
k, r = r.split(b"\0", 1)
except ValueError:
return s
if len(r) < 2:
return s
cf, cm, r = i8(r[0]), i8(r[1]), r[2:]
try:
lang, tk, v = r.split(b"\0", 2)
except ValueError:
return s
if cf != 0:
if cm == 0:
try:
v = _safe_zlib_decompress(v)
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
return s
else:
raise
except zlib.error:
return s
else:
return s
if bytes is not str:
try:
k = k.decode("latin-1", "strict")
lang = lang.decode("utf-8", "strict")
tk = tk.decode("utf-8", "strict")
v = v.decode("utf-8", "strict")
except UnicodeError:
return s
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
self.check_text_memory(len(v))
return s
# --------------------------------------------------------------------
# PNG reader
def on_on_demand_status_event(api, status):
username = status.user.screen_name
status_id = status.id
message = status.text
ImageFile.LOAD_TRUNCATED_IMAGES = True
code = dependency_locator.read_geometrize_script("geometrize_shape_choice_template.chai")
if code == "":
print("Failed to read script")
return
if re.search('Print Geometrize bot status', message, re.IGNORECASE):
print("Received bot status request")
_tweet_message('Geometrize bot status is alive', username, status_id, api)
return
if 'media' in status.entities:
for image in status.entities['media']:
download_filename = 'temp_' + uuid.uuid4().hex + '.png'
download_filepath = dependency_locator.get_geometrize_image_file_absolute_path(download_filename)
result_filepath = dependency_locator.get_geometrize_image_file_absolute_path('geometrized_' + download_filename)
image_data = _download_image(image['media_url'])
if image_data is None:
print("Failed to download tweet image")
continue
image = Image.open(BytesIO(image_data))
if not save_image(image, download_filepath):
print("Failed to save image to filepath " + download_filepath)
continue
geometrize_options = {}
geometrize_options["::IMAGE_INPUT_PATH::"] = download_filepath
geometrize_options["::IMAGE_OUTPUT_PATH::"] = result_filepath
shape_code, shape_quantity_dictionary = tweet_parser.make_code_for_shape_tweet(message)
response_text = tweet_parser.make_message_for_shape_dictionary(shape_quantity_dictionary)
geometrize_options["::IMAGE_TASK_STEP_LOOPS::"] = shape_code
if not geometrize.run_geometrize(code, geometrize_options):
print("Failed to run geometrize")
continue
if not username:
continue
at_username = '@{0}'.format(username)
# Do not tweet @yourself when tweeting images - avoids an infinite tweet loop
if at_username != config.TWITTER_BOT_USERNAME:
_tweet_image(result_filepath, at_username + " " + response_text, status_id, api)
print("Did tweet image")
## Handles a status change event from the Twitter streaming API.
## This means waiting for status updates and doing things to response to them.
def on_account_watcher_status_event(api, status):
username = status.user.screen_name
status_id = status.id
message = status.text
ImageFile.LOAD_TRUNCATED_IMAGES = True
code = dependency_locator.read_geometrize_script("geometrize_shape_choice_template.chai")
if code == "":
print("Failed to read script")
return
if re.search('Print Geometrize bot status', message, re.IGNORECASE):
print("Received bot status request")
_tweet_message('Geometrize bot status is alive', username, status_id, api)
return
if 'media' in status.entities:
for image in status.entities['media']:
download_filename = 'temp_' + uuid.uuid4().hex + '.png'
download_filepath = dependency_locator.get_geometrize_image_file_absolute_path(download_filename)
result_filepath = dependency_locator.get_geometrize_image_file_absolute_path('geometrized_' + download_filename)
image_data = _download_image(image['media_url'])
if image_data is None:
print("Failed to download tweet image")
continue
image = Image.open(BytesIO(image_data))
if not save_image(image, download_filepath):
print("Failed to save image to filepath " + download_filepath)
continue
geometrize_options = {}
geometrize_options["::IMAGE_INPUT_PATH::"] = download_filepath
geometrize_options["::IMAGE_OUTPUT_PATH::"] = result_filepath
shape_code, shape_quantity_dictionary = tweet_parser.make_code_for_shape_tweet(message)
response_text = tweet_parser.make_message_for_shape_dictionary(shape_quantity_dictionary)
geometrize_options["::IMAGE_TASK_STEP_LOOPS::"] = shape_code
if not geometrize.run_geometrize(code, geometrize_options):
print("Failed to run geometrize")
continue
at_username = '@{0}'.format(username)
_tweet_image(result_filepath, response_text, None, api)
print("Did tweet image")
def chunk_iTXt(self, pos, length):
# international text
r = s = ImageFile._safe_read(self.fp, length)
try:
k, r = r.split(b"\0", 1)
except ValueError:
return s
if len(r) < 2:
return s
cf, cm, r = i8(r[0]), i8(r[1]), r[2:]
try:
lang, tk, v = r.split(b"\0", 2)
except ValueError:
return s
if cf != 0:
if cm == 0:
try:
v = _safe_zlib_decompress(v)
except ValueError:
if ImageFile.LOAD_TRUNCATED_IMAGES:
return s
else:
raise
except zlib.error:
return s
else:
return s
if bytes is not str:
try:
k = k.decode("latin-1", "strict")
lang = lang.decode("utf-8", "strict")
tk = tk.decode("utf-8", "strict")
v = v.decode("utf-8", "strict")
except UnicodeError:
return s
self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
self.check_text_memory(len(v))
return s
# --------------------------------------------------------------------
# PNG reader