Photo gallery ordered in Python

Asked

Viewed 290 times

0

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

pessoa_ID_N.jpg

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

my script lists all photos from the folder. what I need to do is either list by 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>
<div class='row'>
  <div class='container-fluid'>
    {% for image in images %}
    <div class='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 have already searched the Python manuals and other functions but when trying to implement the script it stops working. Could someone guide me on how to do or help me with this ?


Problem solved.

follows how Cod looked:

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='::')
  • 1
  • 1

    With what I answered in this other question, just ask sorted(files, key=data_criacao)

  • So Anderson i vo your post and I even managed to run it but I can’t adapt the Sorted in my script. Can you tell me where it would enter please?

  • 1

    In his for, that iterates over the files.

  • Thank you I’ll try and I’ll answer.

  • I did, thank you very much

Show 1 more comment

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='::')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.