|
@@ -67,18 +67,32 @@ def imread_pil(file_or_buffer, to_mode=None):
|
|
return None
|
|
return None
|
|
|
|
|
|
|
|
|
|
-def imwrite_bytes(filename, image_bytes, update_extension=True):
|
|
|
|
|
|
+def imwrite_bytes(filename, image_bytes: bytes, update_extension: bool = True):
|
|
|
|
+ """Write image bytes to file.
|
|
|
|
+
|
|
|
|
+ Args:
|
|
|
|
+ filename: str
|
|
|
|
+ filename which image_bytes is written into.
|
|
|
|
+ image_bytes: bytes
|
|
|
|
+ image content to be written.
|
|
|
|
+ update_extension: bool
|
|
|
|
+ whether update extension according to image_bytes or not.
|
|
|
|
+ the cost of update extension is smaller than update image format.
|
|
|
|
+ """
|
|
extension = imghdr.what('', image_bytes)
|
|
extension = imghdr.what('', image_bytes)
|
|
- if extension is None:
|
|
|
|
- raise ValueError('image_bytes is not image')
|
|
|
|
- extension = '.' + extension
|
|
|
|
file_extension = khandy.get_path_extension(filename)
|
|
file_extension = khandy.get_path_extension(filename)
|
|
- if extension.lower() != file_extension.lower():
|
|
|
|
|
|
+ # imghdr.what fails to determine image format sometimes!
|
|
|
|
+ # so when its return value is None, never update extension.
|
|
|
|
+ if extension is None:
|
|
|
|
+ image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
|
|
|
|
+ image_bytes = cv2.imencode(file_extension, image)[1]
|
|
|
|
+ elif (extension.lower() != file_extension.lower()[1:]):
|
|
if update_extension:
|
|
if update_extension:
|
|
filename = khandy.replace_path_extension(filename, extension)
|
|
filename = khandy.replace_path_extension(filename, extension)
|
|
else:
|
|
else:
|
|
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
|
|
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
|
|
image_bytes = cv2.imencode(file_extension, image)[1]
|
|
image_bytes = cv2.imencode(file_extension, image)[1]
|
|
|
|
+
|
|
with open(filename, "wb") as f:
|
|
with open(filename, "wb") as f:
|
|
f.write(image_bytes)
|
|
f.write(image_bytes)
|
|
return filename
|
|
return filename
|