Skip to content
This repository has been archived by the owner on Mar 14, 2020. It is now read-only.

Commit

Permalink
Fixed bug: QImage failing to detect correct image format caused no co…
Browse files Browse the repository at this point in the history
…ver being generated;

Resolves #106
  • Loading branch information
twiddli committed Feb 15, 2016
1 parent 522dd4b commit 48e2b9d
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 32 deletions.
15 changes: 14 additions & 1 deletion LICENSE-3RD-PARTY
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,17 @@ Redistribution and use in source and binary forms, with or without modification,
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Hardcoded Software Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

---------------------------------------------------------------------------
The Python Imaging Library (PIL) is

Copyright © 1997-2011 by Secret Labs AB
Copyright © 1995-2011 by Fredrik Lundh
---------------------------------------------------------------------------

By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 changes: 18 additions & 3 deletions version/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,13 +608,28 @@ def init_toolbar(self):
# debug specfic code
if app_constants.DEBUG:
def debug_func():
from PyQt5.QtGui import QImageReader
from PIL import Image
from PyQt5.QtGui import QImageReader, QImage
m = QMessageBox(self)
m.setText("{}".format(QImageReader.supportedImageFormats()))
m.exec()
f_n = 'horopic.jpg'
self._lbl = QLabel()
self._lbl.setPixmap(QPixmap('horopic.jpg'))
self._lbl.show()
im_data = utils.PToQImageHelper(f_n)
pic = image = QImage(im_data['data'], im_data['im'].size[0], im_data['im'].size[1], im_data['format'])
if im_data['colortable']:
image.setColorTable(im_data['colortable'])
print("P is null:", pic.isNull())
im = Image.open(f_n)
im.verify()
print("Format:", im.format)
print("Dic:", im.info)
print("Mode:", im.mode)
if pic.isNull():
pic = QImage()
print("New Load P", pic.load(f_n))
#self._lbl.setPixmap(pic)
#self._lbl.show()

debug_btn = QToolButton()
debug_btn.setText("DEBUG BUTTON")
Expand Down
61 changes: 33 additions & 28 deletions version/gallerydb.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@
#along with Happypanda. If not, see <http://www.gnu.org/licenses/>.
#"""

import datetime, os, scandir, threading, logging, queue, io, uuid # for unique filename
import datetime
import os
import scandir
import threading
import logging
import queue
import io
import uuid # for unique filename
import re as regex

from PyQt5.QtCore import Qt, QObject, pyqtSignal
Expand Down Expand Up @@ -133,11 +140,13 @@ def gen_thumbnail(gallery, width=app_constants.THUMB_W_SIZE,
raise IndexError

# Do the scaling

image = QImage()
image.load(img_path)
im_data = utils.PToQImageHelper(img_path)
image = QImage(im_data['data'], im_data['im'].size[0], im_data['im'].size[1], im_data['format'])
if im_data['colortable']:
image.setColorTable(im_data['colortable'])
if image.isNull():
raise IndexError
radius = 5
image = image.scaled(width, height, Qt.KeepAspectRatio, Qt.SmoothTransformation)
r_image = QImage(image.width(), image.height(), QImage.Format_ARGB32)
r_image.fill(Qt.transparent)
Expand All @@ -148,7 +157,7 @@ def gen_thumbnail(gallery, width=app_constants.THUMB_W_SIZE,
p.setRenderHint(p.Antialiasing)
p.setPen(Qt.NoPen)
p.setBrush(QBrush(image))
p.drawRoundedRect(0, 0, r_image.width(), r_image.height(), 5, 5)
p.drawRoundedRect(0, 0, r_image.width(), r_image.height(), radius, radius)
p.end()
r_image.save(new_img_path, "PNG", quality=100)
except IndexError:
Expand Down Expand Up @@ -228,8 +237,7 @@ def default_chap_exec(gallery_or_id, chap, only_values=False):
'chapter_number':chap.number,
'chapter_path':str.encode(chap.path),
'pages':chap.pages,
'in_archive':in_archive}
)
'in_archive':in_archive})
return execute

def default_exec(object):
Expand Down Expand Up @@ -264,8 +272,7 @@ def check(obj):
'times_read':check(object.times_read),
'db_v':check(db_constants.REAL_DB_VERSION),
'exed':check(object.exed)
}
]
}]
return executing

class GalleryDB(DBBase):
Expand Down Expand Up @@ -298,8 +305,7 @@ def rebuild_thumb(gallery):
if gallery.profile:
GalleryDB.clear_thumb(gallery.profile)
gallery.profile = gen_thumbnail(gallery)
GalleryDB.modify_gallery(
gallery.id,
GalleryDB.modify_gallery(gallery.id,
profile=gallery.profile)
except:
log.exception("Failed rebuilding thumbnail")
Expand Down Expand Up @@ -333,8 +339,7 @@ def rebuild_gallery(gallery, thumb=False):
log_i('Rebuilding {}'.format(gallery.title.encode(errors='ignore')))
log_i("Rebuilding gallery {}".format(gallery.id))
HashDB.del_gallery_hashes(gallery.id)
GalleryDB.modify_gallery(
gallery.id,
GalleryDB.modify_gallery(gallery.id,
title=gallery.title,
artist=gallery.artist,
info=gallery.info,
Expand Down Expand Up @@ -869,7 +874,8 @@ def look_exist_tag_map(tag_id):
executing = []
for tags_map in tags_mappings_id_list:
executing.append((series_id, tags_map,))
#cls.execute(cls, 'INSERT INTO series_tags_map(series_id, tags_mappings_id) VALUES(?, ?)', (series_id, tags_map,))
#cls.execute(cls, 'INSERT INTO series_tags_map(series_id, tags_mappings_id)
#VALUES(?, ?)', (series_id, tags_map,))
cls.executemany(cls, 'INSERT OR IGNORE INTO series_tags_map(series_id, tags_mappings_id) VALUES(?, ?)', executing)

@staticmethod
Expand Down Expand Up @@ -1180,7 +1186,7 @@ def gen_gallery_hash(cls, gallery, chapter, page=None, color_img=False, _name=No
skip_gen = True
if page == "mid":
try:
hashes = {'mid':hashes[len(hashes)//2]}
hashes = {'mid':hashes[len(hashes) // 2]}
except KeyError:
skip_gen = False

Expand Down Expand Up @@ -1216,8 +1222,8 @@ def look_exists(page):
if not utils.image_greyscale(imgs[0]):
return {'color':imgs[0]}
if page == 'mid':
imgs = imgs[len(imgs)//2]
pages[len(imgs)//2] = imgs
imgs = imgs[len(imgs) // 2]
pages[len(imgs) // 2] = imgs
elif isinstance(page, list):
for p in page:
pages[p] = imgs[p]
Expand Down Expand Up @@ -1262,7 +1268,7 @@ def look_exists(page):
return {'color':zip.extract(con[0])}
f_bytes.close()
if page == 'mid':
p = len(con)//2
p = len(con) // 2
img = con[p]
pages = {p:zip.open(img, True)}
elif isinstance(page, list):
Expand Down Expand Up @@ -1734,20 +1740,20 @@ def __str__(self):
@property
def next_chapter(self):
try:
return self.parent[self.number+1]
return self.parent[self.number + 1]
except KeyError:
return None

@property
def previous_chapter(self):
try:
return self.parent[self.number-1]
return self.parent[self.number - 1]
except KeyError:
return None

def open(self, stat_msg=True):
if stat_msg:
txt = "Opening chapter {} of {}".format(self.number+1, self.gallery.title)
txt = "Opening chapter {} of {}".format(self.number + 1, self.gallery.title)
app_constants.STAT_MSG_METHOD(txt)
app_constants.NOTIF_BAR.add_text(txt)
if self.in_archive:
Expand Down Expand Up @@ -1888,7 +1894,7 @@ def from_v021_to_v022(self, old_db_path=db_constants.DB_PATH):
log_i("Started rebuilding database")
if DBBase._DB_CONN:
DBBase._DB_CONN.close()
DBBase._DB_CONN= db.init_db(old_db_path)
DBBase._DB_CONN = db.init_db(old_db_path)
db_galleries = add_method_queue(GalleryDB.get_all_gallery, False, False, True, True)
galleries = []
for g in db_galleries:
Expand All @@ -1901,7 +1907,7 @@ def from_v021_to_v022(self, old_db_path=db_constants.DB_PATH):
# get all chapters
log_i("Getting chapters...")
chap_rows = DBBase().execute("SELECT * FROM chapters").fetchall()
data_count = len(chap_rows)*2
data_count = len(chap_rows) * 2
self.DATA_COUNT.emit(data_count)
for n, chap_row in enumerate(chap_rows, -1):
log_d('Next chapter row')
Expand Down Expand Up @@ -1931,7 +1937,7 @@ def from_v021_to_v022(self, old_db_path=db_constants.DB_PATH):
galleries.remove(gallery)
break
self.PROGRESS.emit(n)
log_d("G: {} C:{}".format(len(n_galleries), data_count-1))
log_d("G: {} C:{}".format(len(n_galleries), data_count - 1))
log_i("Database magic...")
if os.path.exists(db_constants.THUMBNAIL_PATH):
for root, dirs, files in scandir.walk(db_constants.THUMBNAIL_PATH, topdown=False):
Expand All @@ -1945,7 +1951,7 @@ def from_v021_to_v022(self, old_db_path=db_constants.DB_PATH):
t_db_path = os.path.join(head, 'temp.db')
conn = db.init_db(t_db_path)
DBBase._DB_CONN = conn
for n, g in enumerate(n_galleries, len(chap_rows)-1):
for n, g in enumerate(n_galleries, len(chap_rows) - 1):
log_d('Adding new gallery')
GalleryDB.add_gallery(g)
self.PROGRESS.emit(n)
Expand Down Expand Up @@ -2072,8 +2078,7 @@ def get_records():
self._fetching = True
remaining = self.count - len(self._current_data)
rec_to_fetch = min(remaining, self._fetch_count)
c = add_method_queue(self._DB.execute, False, 'SELECT * FROM series LIMIT {}, {}'.format(
self._offset, rec_to_fetch))
c = add_method_queue(self._DB.execute, False, 'SELECT * FROM series LIMIT {}, {}'.format(self._offset, rec_to_fetch))
self._offset += rec_to_fetch
if c:
new_data = c.fetchall()
Expand All @@ -2083,7 +2088,7 @@ def get_records():
self.GALLERY_EMITTER.emit(gallery_list)
self._fetching = False
if not self._fetching:
# TODO: redo this?
# TODO: redo this?
thread = threading.Thread(target=get_records, name='DatabaseEmitter')
thread.start()

Expand Down
98 changes: 98 additions & 0 deletions version/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@
import rarfile
import json
import send2trash
import functools
import time

from PyQt5.QtGui import QImage, qRgba
from PIL import Image,ImageChops

import app_constants
Expand Down Expand Up @@ -1071,4 +1074,99 @@ def image_greyscale(filepath):
return False
return True

def PToQImageHelper(im):
"""
The Python Imaging Library (PIL) is
Copyright © 1997-2011 by Secret Labs AB
Copyright © 1995-2011 by Fredrik Lundh
"""
def rgb(r, g, b, a=255):
"""(Internal) Turns an RGB color into a Qt compatible color integer."""
# use qRgb to pack the colors, and then turn the resulting long
# into a negative integer with the same bitpattern.
return (qRgba(r, g, b, a) & 0xffffffff)

def align8to32(bytes, width, mode):
"""
converts each scanline of data from 8 bit to 32 bit aligned
"""

bits_per_pixel = {
'1': 1,
'L': 8,
'P': 8,
}[mode]

# calculate bytes per line and the extra padding if needed
bits_per_line = bits_per_pixel * width
full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)

extra_padding = -bytes_per_line % 4

# already 32 bit aligned by luck
if not extra_padding:
return bytes

new_data = []
for i in range(len(bytes) // bytes_per_line):
new_data.append(bytes[i*bytes_per_line:(i+1)*bytes_per_line] + b'\x00' * extra_padding)

return b''.join(new_data)

data = None
colortable = None

# handle filename, if given instead of image name
if hasattr(im, "toUtf8"):
# FIXME - is this really the best way to do this?
if str is bytes:
im = unicode(im.toUtf8(), "utf-8")
else:
im = str(im.toUtf8(), "utf-8")
if isinstance(im, (bytes, str)):
im = Image.open(im)

if im.mode == "1":
format = QImage.Format_Mono
elif im.mode == "L":
format = QImage.Format_Indexed8
colortable = []
for i in range(256):
colortable.append(rgb(i, i, i))
elif im.mode == "P":
format = QImage.Format_Indexed8
colortable = []
palette = im.getpalette()
for i in range(0, len(palette), 3):
colortable.append(rgb(*palette[i:i+3]))
elif im.mode == "RGB":
data = im.tobytes("raw", "BGRX")
format = QImage.Format_RGB32
elif im.mode == "RGBA":
try:
data = im.tobytes("raw", "BGRA")
except SystemError:
# workaround for earlier versions
r, g, b, a = im.split()
im = Image.merge("RGBA", (b, g, r, a))
format = QImage.Format_ARGB32
else:
raise ValueError("unsupported image mode %r" % im.mode)

# must keep a reference, or Qt will crash!
__data = data or align8to32(im.tobytes(), im.size[0], im.mode)
return {
'data': __data, 'im': im, 'format': format, 'colortable': colortable
}

def timeit(func):
@functools.wraps(func)
def newfunc(*args, **kwargs):
startTime = time.time()
func(*args, **kwargs)
elapsedTime = time.time() - startTime
print('function [{}] finished in {} ms'.format(
func.__name__, int(elapsedTime * 1000)))
return newfunc

0 comments on commit 48e2b9d

Please sign in to comment.