Photo Gallery sorted in Python

1

Good morning I'm developing a gallery of images listing them from a directory. What I need to do is separate these images or sort them in order of creation. I have a script that generates the images as follows.

pessoa_ID_N.jpg

where ID is the id number of the person and N is the photo number of this person that can range from 0 to 9.

My script lists all the photos in the folder. what I need to do is either list the creation order or separate with a <hr> each set of ID's created.

My cod:

#!/bin/python

import os
from flask import Flask, Response, request, abort, render_template_string, send_from_directory
from PIL import Image
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO


app = Flask(__name__)

WIDTH = 1000
HEIGHT = 800

TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <style>
body {
    margin: 0;
    background-color: #333;
    overflow-x:hidden;
}
.img-responsive{
        max-width:100%;
}
    </style>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"charset="utf-8"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K$
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.10.0/css/lightbox.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.10.0/js/lightbox.min.js"></script></head><body><divclass='row'><divclass='container-fluid'>{%forimageinimages%}<divclass='col-md-2'style="min-height:300px">
        <a class="image" href="{{ image.src }}" style="width: {{ image.width }}px; height: {{ image.height }}px" data-lightbox="faces">
            <img src="{{ image.src }}" data-src="{{ image.src }}?w={{ image.width }}&amp;h={{ image.height }}" class="img-responsive" />
        </a>
    </div>
    {% endfor %}
 </div>
</div>
</body>
'''

@app.route('/<path:filename>')
def image(filename):
    try:
        w = int(request.args['w'])
        h = int(request.args['h'])
    except (KeyError, ValueError):
        return send_from_directory('.', filename)

    try:
        im = Image.open(filename)
        im.thumbnail((w, h), Image.ANTIALIAS)
        io = StringIO.StringIO()
        im.save(io, format='JPEG')
        return Response(io.getvalue(), mimetype='image/jpeg')

    except IOError:
        abort(404)

    return send_from_directory('.', filename)

@app.route('/')
def index():
    images = []
    for root, dirs, files in os.walk('.'):
        for filename in [os.path.join(root, name) for name in files]:
            if not filename.endswith('.jpg'):
                continue
            im = Image.open(filename)
            w, h = im.size
            aspect = 1.0*w/h
            if aspect > 1.0*WIDTH/HEIGHT:
                width = min(w, WIDTH)
                height = width/aspect
            else:
                height = min(h, HEIGHT)
                width = height*aspect
            images.append({
                'width': int(width),
                'height': int(height),
                'src': filename
            })

    return render_template_string(TEMPLATE, **{
        'images': images
    })

if __name__ == '__main__':
    app.run(debug=True, host='::')

I already looked in the Python manuals and other functions but when trying to implement the script to work. Could someone guide me on how to do or give a help with this?

Problem solved.

The code is as follows:

def index():
    images = []
    for root, dirs, files in os.walk('.'):
        files.sort(key=os.path.getmtime)
        for filename in [os.path.join(root, name) for name in files]:
            if not filename.endswith('.jpg'):
                continue
            im = Image.open(filename)
            w, h = im.size
            aspect = 1.0*w/h
            if aspect > 1.0*WIDTH/HEIGHT:
                width = min(w, WIDTH)
                height = width/aspect
            else:
                height = min(h, HEIGHT)
                width = height*aspect
            images.append({
                'width': int(width),
                'height': int(height),
                'src': filename
            })

    return render_template_string(TEMPLATE, **{
        'images': images
    })

if __name__ == '__main__':
    app.run(debug=True, host='::')
    
asked by anonymous 22.08.2018 / 14:22

1 answer

0

Thanks to Anderson's help, the working cod was as follows:

def index():
    images = []
    for root, dirs, files in os.walk('.'):
        files.sort(key=os.path.getmtime)
        for filename in [os.path.join(root, name) for name in files]:
            if not filename.endswith('.jpg'):
                continue
            im = Image.open(filename)
            w, h = im.size
            aspect = 1.0*w/h
            if aspect > 1.0*WIDTH/HEIGHT:
                width = min(w, WIDTH)
                height = width/aspect
            else:
                height = min(h, HEIGHT)
                width = height*aspect
            images.append({
                'width': int(width),
                'height': int(height),
                'src': filename
            })

    return render_template_string(TEMPLATE, **{
        'images': images
    })

if __name__ == '__main__':
    app.run(debug=True, host='::')
    
22.08.2018 / 14:39