1
1
Fork 0

Even more better image generation,

new jpeg image variant
dev
Jan Kužílek 5 years ago
parent b09550a522
commit 875abc5516

@ -17,16 +17,18 @@ def create_app():
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(POST_UPLOADS=os.path.join(app.instance_path, 'post'), SQLALCHEMY_TRACK_MODIFICATIONS=False)
try:
os.makedirs(app.instance_path)
# try:
# os.makedirs(app.instance_path)
# os.makedirs(app.config.get('POST_UPLOADS'))
for d in ['img', 'jpeg', 'sample', 'thumb']:
os.makedirs(os.path.join(app.config.get('POST_UPLOADS'), d))
# # os.makedirs(app.config.get('POST_UPLOADS'))
# for d in ['img', 'jpeg', 'sample', 'thumb']:
# os.makedirs(os.path.join(app.config.get('POST_UPLOADS'), d))
# shutil.copyfile(os.path.join(app.root_path, 'config.def.py'), os.path.join(app.instance_path, 'config.py'))
except OSError:
pass
# # shutil.copyfile(os.path.join(app.root_path, 'config.def.py'), os.path.join(app.instance_path, 'config.py'))
# except OSError:
# pass
## TO REDO
app.config.from_pyfile('config.py')

@ -19,7 +19,10 @@ def uploaded_img(path, store='img', exten=None):
filename = path.split('/')[0].split('.')[0]
# print(os.path.join(current_app.config.get('POST_UPLOADS'), store, "{}{}".format(filename, ext)))
return send_from_directory(os.path.join(current_app.config.get('POST_UPLOADS'), store), "{}{}".format(filename, ext))
return send_from_directory(
os.path.join(current_app.config.get('POST_UPLOADS'), store),
"{}{}".format(filename, ext)
)
@bp.route('/jpeg/<path:path>')
def uploaded_jpeg(*args, **kwargs):
@ -29,20 +32,15 @@ def uploaded_jpeg(*args, **kwargs):
def uploaded_sample(*args, **kwargs):
return uploaded_img(*args, **kwargs, store='sample', exten='jpg')
@bp.route('/bigthumb/<path:path>')
def uploaded_big_thumb(*args, **kwargs):
return uploaded_img(*args, **kwargs, store='thumb_big', exten='jpg')
@bp.route('/thumb/<path:path>')
def uploaded_thumb(*args, **kwargs):
def uploaded_smol_thumb(*args, **kwargs):
return uploaded_img(*args, **kwargs, store='thumb', exten='jpg')
# @bp.route('/threads')
# def threads():
# return render_template('post/index.html')
# @bp.route('/user/show/<username>')
# def user_profile(username):
# pass
# @bp.route('/user/settings')
# @login_required
# def user_settings():
# pass

@ -47,6 +47,7 @@ def posts(page):
posts = posts_query.paginate(page, current_app.config.get('POSTS_PER_PAGE'))
tags = tags_prepare(posts.items)
# BRUH
session['index_settings'] = dict(tags=request.args.get('tags', ''), rating=f_rating.name)
return render_template('post/index.html', posts=posts, tags=tags)
@ -130,12 +131,14 @@ def upload():
form = UploadForm(request.form)
if request.method == 'POST' and form.validate():
file = request.files.get(form.post_img.name)
# file.data = io.BytesIO(file.read())
file.seek(0)
file.save(post.image_files['image'])
f_tags = form.tags.data.split()
tags = Tag.query.filter(Tag.content.in_(f_tags)).all()
post = Post(file, **Post.fileinfo(file), source=form.sauce.data, tags=tags, rating=form.rating.data, author=current_user)
post.generate_image_files()
db.session.add(post)
db.session.commit()
@ -190,7 +193,7 @@ def posts_api():
md5=p.md5,
file_size=p.filesize,
file_url=p.url(path=p.file_uri, endpoint='img'),
preview_url=p.url(path=p.file_uri, endpoint='thumb'),
preview_url=p.url(path=p.file_uri, endpoint='thumb_big'),
preview_width=0,
preview_height=0,
@ -203,7 +206,7 @@ def posts_api():
sample_height=0,
sample_file_size=0,
jpeg_url=p.url(path=p.file_uri, endpoint='img') if p.filetype is FILETYPE.jpeg else p.url(path=p.file_uri, endpoint='jpeg'),
jpeg_url=p.url(path=p.file_uri, endpoint='img') if p.filetype.is_jpeg else p.url(path=p.file_uri, endpoint='jpeg'),
jpeg_width=0,
jpeg_height=0,
@ -223,4 +226,4 @@ def posts_api():
frames_pending=[],
frames_string='',
frames=[]
) for p in posts.items])
) for p in posts.items])

@ -29,6 +29,14 @@ class FILETYPE(enum.Enum):
png = 0
jpeg = 1
@property
def file_ext(self):
return 'png' if self is FILETYPE.png else 'jpg'
@property
def is_jpeg(self):
return self == FILETYPE.jpeg
class RATING(enum.Enum):
safe = 0
questionable = 1
@ -182,19 +190,19 @@ class Post(TimestampMixin, db.Model):
#tags = db.relationship('Tag', secondary=post_tags, back_populates='posts')
tags = db.relationship('Tag', secondary=post_tags, backref=db.backref('posts'))
def __init__(self, file, **kwargs):
super().__init__(**kwargs)
# def __init__(self, **kwargs):
# super().__init__(**kwargs)
# self.md5 = hashlib.md5(file.data.getbuffer()).hexdigest()
# self.filetype = FILETYPE[file.mimetype.split('/')[1]]
# # self.md5 = hashlib.md5(file.data.getbuffer()).hexdigest()
# # self.filetype = FILETYPE[file.mimetype.split('/')[1]]
# with Image.open(file.data) as im:
# self.width, self.height = im.width, im.height
# self.filesize = file.data.getbuffer().nbytes
# # with Image.open(file.data) as im:
# # self.width, self.height = im.width, im.height
# # self.filesize = file.data.getbuffer().nbytes
# self.origin_filename = file.filename
# # self.origin_filename = file.filename
self.generate_image_files(file)
# self.generate_image_files()
@property
def resolution(self):
@ -214,25 +222,24 @@ class Post(TimestampMixin, db.Model):
origin_filename=file.filename
)
def generate_image_files(self, file):
# with open(self.image_files['image'], "wb") as f:
# f.write(file.data.getbuffer())
file.seek(0)
file.save(self.image_files['image'])
with Image.open(file) as im:
def generate_image_files(self):
with Image.open(self.image_files['image']) as im:
im = im.convert('RGB')
if self.image_files['jpeg'] is not None:
im.save(self.image_files['jpeg'], 'JPEG', quality=80)
im.save(self.image_files['jpeg'], 'JPEG', quality=90) # SUM QUALITY, YEEES
sim = im.copy()
sim.thumbnail([1500,1500])
sim.save(self.image_files['sample'], 'JPEG', quality=80)
sim = im.copy()
sim.thumbnail([800,800])
sim.save(self.image_files['sample'], 'JPEG', quality=80)
sim.save(self.image_files['thumb_big'], 'JPEG', quality=80)
sim = im.copy()
sim.thumbnail([512,512])
sim.save(self.image_files['thumb'], 'JPEG', quality=80)
sim.save(self.image_files['thumb_smol'], 'JPEG', quality=80)
def remove_image_files(self):
for im in self.image_files.values():
@ -244,30 +251,45 @@ class Post(TimestampMixin, db.Model):
@property
def image_files(self):
return dict(
image=os.path.join(current_app.config.get('POST_UPLOADS'), 'img', "{}.{}".format(self.md5, 'jpg' if self.filetype is FILETYPE.jpeg else 'png')),
jpeg=(None if self.filetype is FILETYPE.jpeg else os.path.join(current_app.config.get('POST_UPLOADS'), 'jpeg', "{}.{}".format(self.md5, 'jpg'))),
# image=os.path.join(current_app.config.get('POST_UPLOADS'), 'img', "{}.{}".format(self.md5, 'jpg' if self.filetype is FILETYPE.jpeg else 'png')),
image=os.path.join(current_app.config.get('POST_UPLOADS'), 'img', "{}.{}".format(self.md5, self.filetype.file_ext)),
jpeg=(None if self.filetype.is_jpeg else os.path.join(current_app.config.get('POST_UPLOADS'), 'jpeg', "{}.{}".format(self.md5, 'jpg'))),
sample=os.path.join(current_app.config.get('POST_UPLOADS'), 'sample', "{}.{}".format(self.md5, 'jpg')),
thumb=os.path.join(current_app.config.get('POST_UPLOADS'), 'thumb', "{}.{}".format(self.md5, 'jpg'))
thumb_big=os.path.join(current_app.config.get('POST_UPLOADS'), 'thumb_big', "{}.{}".format(self.md5, 'jpg')),
thumb_smol=os.path.join(current_app.config.get('POST_UPLOADS'), 'thumb', "{}.{}".format(self.md5, 'jpg'))
)
def __repr__(self):
return('<Post #{} by {}, {} of {} bytes>'.format(self.id, self.author, self.filetype.name, self.filesize))
@property
def file_uri(self):
# filename = "{}.{}".format('maybe_later_generated_cute_filename', 'jpg' if self.filetype is FILETYPE.jpeg else 'png')
# filename = 'maybe_later_generated_cute_filename'
filename = "{} - {} {}".format(current_app.config.get('INSTANCE_NAME'), self.id, " ".join(tag.content.replace(' ', '_') for tag in self.tags))
return os.path.join(self.md5, filename)
def url(self, path, endpoint='img'):
if endpoint == 'img':
return url_for('main.uploaded_img', path="{}.{}".format(path,'jpg' if self.filetype is FILETYPE.jpeg else 'png'))
return url_for(
'main.uploaded_img',
path="{}.{}".format(path, self.filetype.file_ext)
)
elif endpoint == 'jpeg':
return url_for('main.uploaded_jpeg' if not self.filetype is FILETYPE.jpeg else 'main.uploaded_img', path="{}.{}".format(path,'jpg'))
return url_for(
'main.uploaded_jpeg' if not self.filetype.is_jpeg else 'main.uploaded_img',
path="{}.{}".format(path,'jpg')
)
elif endpoint == 'sample':
return url_for('main.uploaded_sample', path="{}.{}".format(path,'jpg'))
elif endpoint == 'thumb_big':
return url_for('main.uploaded_big_thumb', path="{}.{}".format(path,'jpg'))
elif endpoint == 'thumb':
return url_for('main.uploaded_thumb', path="{}.{}".format(path,'jpg'))
return url_for('main.uploaded_smol_thumb', path="{}.{}".format(path,'jpg'))
@property
def file_uri(self):
return os.path.join(
self.md5,
"{} - {} {}".format(
current_app.config.get('INSTANCE_NAME'),
self.id,
" ".join(tag.content.replace(' ', '_') for tag in self.tags)
)
)
def __repr__(self):
return('<Post #{} by {}, {} of {} bytes>'.format(self.id, self.author, self.filetype.name, self.filesize))
@cached_property
def flex(self):

@ -9,7 +9,7 @@
{% for post in posts.items %}
<figure style="{{ post.flex }}">
<a href="{{ url_for('post.post_show', id=post.id) }}">
<img src="{{ post.url(path=post.file_uri, endpoint='thumb') }}" srcset="{{ post.url(path=post.file_uri, endpoint='thumb') }} 512w, {{ post.url(path=post.file_uri, endpoint='sample') }} 800w" alt=""> <!--sizes="(min-width: 513px) 1000w" -->
<img src="{{ post.url(path=post.file_uri, endpoint='thumb') }}" srcset="{{ post.url(path=post.file_uri, endpoint='thumb') }} 512w, {{ post.url(path=post.file_uri, endpoint='thumb_big') }} 800w" alt=""> <!--sizes="(min-width: 513px) 1000w" -->
</a>
</figure>
{% endfor %}

@ -22,7 +22,7 @@
<div class="resolution">Image res: {{ post.image_resolution }}</div>
<div class="jpeg"><a href="{{ post.url(path=post.file_uri, endpoint='jpeg') }}">Enlarge image</a></div>
{% if post.filetype.name == 'png' %}
{% if not post.filetype.is_jpeg %}
<div class="png"><a href="{{ post.url(path=post.file_uri) }}">Original PNG file</a></div>
{% endif %}
</article>
@ -54,7 +54,7 @@
{% block main_content %}
<section class="post-single">
<div class="image">
<img src="{{ post.url(path=post.file_uri, endpoint='jpeg') }}" alt="">
<img src="{{ post.url(path=post.file_uri, endpoint='sample') }}" alt="">
</div>
</section>
{% endblock %}

Loading…
Cancel
Save