| 86 | |
| 87 | # Create drafty representation of a message with an inline image. |
| 88 | def inline_image(filename): |
| 89 | try: |
| 90 | im = Image.open(filename, 'r') |
| 91 | width = im.width |
| 92 | height = im.height |
| 93 | format = im.format if im.format else "JPEG" |
| 94 | if width > MAX_IMAGE_DIM or height > MAX_IMAGE_DIM: |
| 95 | # Scale the image |
| 96 | scale = min(min(width, MAX_IMAGE_DIM) / width, min(height, MAX_IMAGE_DIM) / height) |
| 97 | width = int(width * scale) |
| 98 | height = int(height * scale) |
| 99 | resized = im.resize((width, height)) |
| 100 | im.close() |
| 101 | im = resized |
| 102 | |
| 103 | mimetype = 'image/' + format.lower() |
| 104 | bitbuffer = memory_io() |
| 105 | im.save(bitbuffer, format=format) |
| 106 | data = base64.b64encode(bitbuffer.getvalue()) |
| 107 | |
| 108 | # python3 fix. |
| 109 | if type(data) is not str: |
| 110 | data = data.decode() |
| 111 | |
| 112 | result = { |
| 113 | 'txt': ' ', |
| 114 | 'fmt': [{'len': 1}], |
| 115 | 'ent': [{'tp': 'IM', 'data': |
| 116 | {'val': data, 'mime': mimetype, 'width': width, 'height': height, |
| 117 | 'name': os.path.basename(filename)}}] |
| 118 | } |
| 119 | im.close() |
| 120 | return result |
| 121 | except IOError as err: |
| 122 | stdoutln("Failed processing image '" + filename + "':", err) |
| 123 | return None |
| 124 | |
| 125 | |
| 126 | # Create a drafty message with an *in-band* attachment. |