Python PIL.Image.MIME Examples

The following are 3 code examples of PIL.Image.MIME(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.Image , or try the search function .
Example #1
Source File: web.py    From bard with GNU General Public License v3.0 6 votes vote down vote up
def api_v1_coverart_song(songID):
    songs = getSongs(songID=songID)
    if not songs:
        abort(404)
    song = songs[0]
    print('Delivering coverart of song %s: %s' % (songID, song.path()))
    coverart = song.getCoverImage()
    if isinstance(coverart, str):
        return send_file(coverart)
    elif isinstance(coverart, tuple):
        image, data = coverart
        response = Response(data, status=200)
        return response
    elif isinstance(coverart, Image.Image):
        data = coverart.tobytes()
        mime = Image.MIME[coverart.format]
        response = Response(data, status=200, mimetype=mime)
        response.headers["Content-Type"] = mime
        return response

    return '' 
Example #2
Source File: views.py    From tyler with GNU General Public License v3.0 5 votes vote down vote up
def get_image(request):

    map_form = MapForm(request.GET)
    if not map_form.is_valid():
        return HttpResponse(json.dumps(map_form.errors), mimetype='application/json', status=400)

    image_data = cached_get_image(**map_form.cleaned_data)

    format = map_form.cleaned_data['format'].upper()
    if format not in Image.MIME:
        raise ValidationError("Unsupported format: %s" % format)
    return HttpResponse(image_data, mimetype=Image.MIME[format]) 
Example #3
Source File: fb2html.py    From fb2mobi with MIT License 4 votes vote down vote up
def parse_binary(self, elem):
        if 'id' in elem.attrib:
            self.log.debug('Parsing binary {0}'.format(elem.attrib))
            have_file = False
            elid = elem.attrib['id']
            decl_type = elem.attrib['content-type'].lower() if 'content-type' in elem.attrib else '---empty---'
            buff = base64.b64decode(elem.text.encode('ascii'))
            try:
                img = Image.open(io.BytesIO(buff))
                real_type = Image.MIME[img.format]
                imgfmt = img.format.lower()
                filename = "bin{0:08}.{1}".format(self.image_count, imgfmt.lower().replace('jpeg', 'jpg'))
                full_name = os.path.join(os.path.join(self.temp_content_dir, 'images'), filename)
                make_dir(full_name)

                if self.kindle and not imgfmt in ('gif', 'jpeg', 'png', 'bmp'):
                    self.log.warning('Image type "{0}" for ref-id "{1} is not supported by your device. Ignoring...'.format(real_type, elid))
                    return

                if real_type != decl_type:
                    self.log.warning('Declared and detected image types for ref-id "{0}" do not match: "{1}" is not "{2}". Using detected type...'.format(elid, decl_type, real_type))

                if self.removepngtransparency and imgfmt == 'png' and (img.mode in ('RGBA', 'LA') or (img.mode in ('RGB', 'L', 'P') and 'transparency' in img.info)):
                    try:
                        self.log.debug('Removing image transparency for ref-id "{0}" in file "{1}"'.format(elid, filename))
                        if img.mode == "P" and isinstance(img.info.get("transparency"), bytes):
                            img = img.convert("RGBA")
                        if img.mode in ("L", "LA"):
                            bg = Image.new("L", img.size, 255)
                        else:
                            bg = Image.new("RGB", img.size, (255, 255, 255))
                        alpha = img.convert("RGBA").split()[-1]
                        bg.paste(img, mask=alpha)
                        bg.save(full_name, dpi=img.info.get("dpi"))
                        have_file = True
                    except:
                        self.log.warning('Unable to remove transparency for ref-id "{0}" in file "{1}"'.format(elid, filename))
                        self.log.debug('Getting details:', exc_info=True)

                self.image_count += 1

            except:
                # Pillow does not recognize SVG files
                if decl_type.split('/')[1].lower() == 'svg':
                    real_type = 'image/svg+xml'
                    filename = "bin{0:08}.svg".format(self.image_count)
                    full_name = os.path.join(os.path.join(self.temp_content_dir, 'images'), filename)
                    self.image_count += 1
                else:
                    self.log.error('Unable to process binary for ref-id "{0}". Skipping...'.format(elid))
                    # self.log.debug('Getting details:', exc_info=True)
                    return

            if not have_file:
                write_file_bin(buff, full_name)

            self.image_file_list.append((elid, real_type, filename))