本文整理汇总了Python中PyQt4.Qt.QImage.loadFromData方法的典型用法代码示例。如果您正苦于以下问题:Python QImage.loadFromData方法的具体用法?Python QImage.loadFromData怎么用?Python QImage.loadFromData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.Qt.QImage
的用法示例。
在下文中一共展示了QImage.loadFromData方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cover
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def cover(self, path, as_file=False, as_image=False,
as_path=False):
path = os.path.join(self.library_path, path, 'cover.jpg')
ret = None
if os.access(path, os.R_OK):
try:
f = lopen(path, 'rb')
except (IOError, OSError):
time.sleep(0.2)
f = lopen(path, 'rb')
with f:
if as_path:
pt = PersistentTemporaryFile('_dbcover.jpg')
with pt:
shutil.copyfileobj(f, pt)
return pt.name
if as_file:
ret = SpooledTemporaryFile(SPOOL_SIZE)
shutil.copyfileobj(f, ret)
ret.seek(0)
else:
ret = f.read()
if as_image:
from PyQt4.Qt import QImage
i = QImage()
i.loadFromData(ret)
ret = i
return ret
示例2: render_cover
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def render_cover(self, book_id):
if self.ignore_render_requests.is_set():
return
tcdata, timestamp = self.thumbnail_cache[book_id]
use_cache = False
if timestamp is None:
# Not in cache
has_cover, cdata, timestamp = self.model().db.new_api.cover_or_cache(book_id, 0)
else:
has_cover, cdata, timestamp = self.model().db.new_api.cover_or_cache(book_id, timestamp)
if has_cover and cdata is None:
# The cached cover is fresh
cdata = tcdata
use_cache = True
if has_cover:
p = QImage()
p.loadFromData(cdata, CACHE_FORMAT if cdata is tcdata else "JPEG")
if p.isNull() and cdata is tcdata:
# Invalid image in cache
self.thumbnail_cache.invalidate((book_id,))
self.update_item.emit(book_id)
return
cdata = None if p.isNull() else p
if not use_cache: # cache is stale
if cdata is not None:
width, height = p.width(), p.height()
scaled, nwidth, nheight = fit_image(
width, height, self.delegate.cover_size.width(), self.delegate.cover_size.height()
)
if scaled:
if self.ignore_render_requests.is_set():
return
p = p.scaled(nwidth, nheight, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
cdata = p
# update cache
if cdata is None:
self.thumbnail_cache.invalidate((book_id,))
else:
try:
self.thumbnail_cache.insert(book_id, timestamp, image_to_data(cdata))
except EncodeError as err:
self.thumbnail_cache.invalidate((book_id,))
prints(err)
except Exception:
import traceback
traceback.print_exc()
elif tcdata is not None:
# Cover was removed, but it exists in cache, remove from cache
self.thumbnail_cache.invalidate((book_id,))
self.delegate.cover_cache.set(book_id, cdata)
self.update_item.emit(book_id)
示例3: render_cover
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def render_cover(self, book_id):
cdata = self.model().db.new_api.cover(book_id)
if self.ignore_render_requests.is_set():
return
if cdata is not None:
p = QImage()
p.loadFromData(cdata)
cdata = None
if not p.isNull():
width, height = p.width(), p.height()
scaled, nwidth, nheight = fit_image(width, height, self.delegate.cover_size.width(), self.delegate.cover_size.height())
if scaled:
if self.ignore_render_requests.is_set():
return
p = p.scaled(nwidth, nheight, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
cdata = p
self.delegate.cover_cache.set(book_id, cdata)
self.update_item.emit(book_id)
示例4: __call__
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def __call__(self, container):
from PyQt4.Qt import QImage
from calibre.gui2 import pixmap_to_data
ext = container.mime_map[self.name].split('/')[-1].upper()
if ext == 'JPG':
ext = 'JPEG'
if ext not in ('PNG', 'JPEG', 'GIF'):
return False
with container.open(self.name, 'r+b') as f:
raw = f.read()
i = QImage()
i.loadFromData(raw)
if i.isNull():
return False
raw = pixmap_to_data(i, format=ext, quality=95)
f.seek(0)
f.truncate()
f.write(raw)
return True
示例5: dropEvent
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def dropEvent(self, event):
event.setDropAction(Qt.CopyAction)
md = event.mimeData()
x, y = dnd_get_image(md)
if x is not None:
# We have an image, set cover
event.accept()
if y is None:
# Local image
self.undo_stack.push(Replace(x.toImage(), _('Drop image'), self))
else:
d = DownloadDialog(x, y, self.gui)
d.start_download()
if d.err is None:
with open(d.fpath, 'rb') as f:
img = QImage()
img.loadFromData(f.read())
if not img.isNull():
self.undo_stack.push(Replace(img, _('Drop image'), self))
event.accept()
示例6: cover
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def cover(self, book_id,
as_file=False, as_image=False, as_path=False):
'''
Return the cover image or None. By default, returns the cover as a
bytestring.
WARNING: Using as_path will copy the cover to a temp file and return
the path to the temp file. You should delete the temp file when you are
done with it.
:param as_file: If True return the image as an open file object (a SpooledTemporaryFile)
:param as_image: If True return the image as a QImage object
:param as_path: If True return the image as a path pointing to a
temporary file
'''
if as_file:
ret = SpooledTemporaryFile(SPOOL_SIZE)
if not self.copy_cover_to(book_id, ret):
return
ret.seek(0)
elif as_path:
pt = PersistentTemporaryFile('_dbcover.jpg')
with pt:
if not self.copy_cover_to(book_id, pt):
return
ret = pt.name
else:
buf = BytesIO()
if not self.copy_cover_to(book_id, buf):
return
ret = buf.getvalue()
if as_image:
from PyQt4.Qt import QImage
i = QImage()
i.loadFromData(ret)
ret = i
return ret
示例7: updateImages
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def updateImages(self, buffer_limit=20):
try:
db_connection = pymysql.connect(self.host, self.user, self.passwd, self.db)
except:
print("Database connection not available")
return
sqlquery = "SELECT `categoryOrder`, `userID`, `dayID`, `comment`, `timestamp`, `eventID` FROM `pictures` WHERE `eventID`>=" + str(self.eventID) + " AND `timestamp`>'" + str(self.mostRecent) + "' ORDER BY `timestamp` ASC"
#print(sqlquery)
try:
with db_connection.cursor() as cursor:
cursor.execute(sqlquery)
result = cursor.fetchall()
for entry in result:
print(entry[4])
#print(self.mostRecent)
if entry[4] > self.mostRecent:
if entry[0] == 0:
print("BREAKING")
continue
self.mostRecent = entry[4]
image_url = "http://voivoi.eventfive.de/events/" + str(entry[5]) + "/uploads/" + str(entry[0]) + "_" + str(entry[1]) + "_" + str(entry[2]) + ".jpg"
req = self.httpPool.request('GET',image_url)
if req.status == 200:
data = req.data
print("Newer file downloaded")
might_be_image = QImage()
if might_be_image.loadFromData(data) :
#print("URL is valid")
self.drawOverlay(might_be_image, entry)
if len(self.imgList) > buffer_limit-1: #TODO: change behaviour to iteration over fixed list, to prevent jumps
self.imgList.pop(1)
self.imgList.append(might_be_image)
finally:
print("Update done, closing connection")
db_connection.close()
示例8: to_png
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def to_png(bmp):
# ImageMagick does not convert some bmp files correctly, while Qt does,
# so try Qt first. See for instance:
# https://bugs.launchpad.net/calibre/+bug/934167
# ImageMagick bug report:
# http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=20350
from PyQt4.Qt import QImage, QByteArray, QBuffer
i = QImage()
if i.loadFromData(bmp):
ba = QByteArray()
buf = QBuffer(ba)
buf.open(QBuffer.WriteOnly)
i.save(buf, "png")
return bytes(ba.data())
from calibre.utils.magick import Image
img = Image()
img.load(bmp)
return img.export("png")
示例9: _fetch_marvin_cover
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def _fetch_marvin_cover(border_width=0):
'''
Retrieve LargeCoverJpg from cache
'''
#self._log_location('border_width: {0}'.format(border_width))
con = sqlite3.connect(self.marvin_db_path)
with con:
con.row_factory = sqlite3.Row
# Fetch Hash from mainDb
cover_cur = con.cursor()
cover_cur.execute('''SELECT
Hash
FROM Books
WHERE ID = '{0}'
'''.format(self.book_id))
row = cover_cur.fetchone()
book_hash = row[b'Hash']
large_covers_subpath = self.connected_device._cover_subpath(size="large")
cover_path = '/'.join([large_covers_subpath, '%s.jpg' % book_hash])
stats = self.parent.ios.exists(cover_path)
if stats:
self._log("fetching large cover from cache")
#self._log("cover size: {:,} bytes".format(int(stats['st_size'])))
cover_bytes = self.parent.ios.read(cover_path, mode='rb')
m_image = QImage()
m_image.loadFromData(cover_bytes)
if border_width:
# Construct a QPixmap with oversized yellow background
m_image = m_image.scaledToHeight(
self.COVER_ICON_SIZE - border_width * 2,
Qt.SmoothTransformation)
self.m_pixmap = QPixmap(
QSize(m_image.width() + border_width * 2,
m_image.height() + border_width * 2))
m_painter = QPainter(self.m_pixmap)
m_painter.setRenderHints(m_painter.Antialiasing)
m_painter.fillRect(self.m_pixmap.rect(), self.MISMATCH_COLOR)
m_painter.drawImage(border_width,
border_width,
m_image)
else:
m_image = m_image.scaledToHeight(
self.COVER_ICON_SIZE,
Qt.SmoothTransformation)
self.m_pixmap = QPixmap(
QSize(m_image.width(),
m_image.height()))
m_painter = QPainter(self.m_pixmap)
m_painter.setRenderHints(m_painter.Antialiasing)
m_painter.drawImage(0, 0, m_image)
self.marvin_cover.setPixmap(self.m_pixmap)
else:
# No cover available, use generic
self._log("No cached cover, using generic")
pixmap = QPixmap()
pixmap.load(I('book.png'))
pixmap = pixmap.scaled(self.COVER_ICON_SIZE,
self.COVER_ICON_SIZE,
aspectRatioMode=Qt.KeepAspectRatio,
transformMode=Qt.SmoothTransformation)
self.marvin_cover.setPixmap(pixmap)
示例10: _populate_covers
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def _populate_covers(self):
'''
Display calibre cover for both unless mismatch
'''
def _fetch_marvin_cover(border_width=0):
'''
Retrieve LargeCoverJpg from cache
'''
#self._log_location('border_width: {0}'.format(border_width))
con = sqlite3.connect(self.marvin_db_path)
with con:
con.row_factory = sqlite3.Row
# Fetch Hash from mainDb
cover_cur = con.cursor()
cover_cur.execute('''SELECT
Hash
FROM Books
WHERE ID = '{0}'
'''.format(self.book_id))
row = cover_cur.fetchone()
book_hash = row[b'Hash']
large_covers_subpath = self.connected_device._cover_subpath(size="large")
cover_path = '/'.join([large_covers_subpath, '%s.jpg' % book_hash])
stats = self.parent.ios.exists(cover_path)
if stats:
self._log("fetching large cover from cache")
#self._log("cover size: {:,} bytes".format(int(stats['st_size'])))
cover_bytes = self.parent.ios.read(cover_path, mode='rb')
m_image = QImage()
m_image.loadFromData(cover_bytes)
if border_width:
# Construct a QPixmap with oversized yellow background
m_image = m_image.scaledToHeight(
self.COVER_ICON_SIZE - border_width * 2,
Qt.SmoothTransformation)
self.m_pixmap = QPixmap(
QSize(m_image.width() + border_width * 2,
m_image.height() + border_width * 2))
m_painter = QPainter(self.m_pixmap)
m_painter.setRenderHints(m_painter.Antialiasing)
m_painter.fillRect(self.m_pixmap.rect(), self.MISMATCH_COLOR)
m_painter.drawImage(border_width,
border_width,
m_image)
else:
m_image = m_image.scaledToHeight(
self.COVER_ICON_SIZE,
Qt.SmoothTransformation)
self.m_pixmap = QPixmap(
QSize(m_image.width(),
m_image.height()))
m_painter = QPainter(self.m_pixmap)
m_painter.setRenderHints(m_painter.Antialiasing)
m_painter.drawImage(0, 0, m_image)
self.marvin_cover.setPixmap(self.m_pixmap)
else:
# No cover available, use generic
self._log("No cached cover, using generic")
pixmap = QPixmap()
pixmap.load(I('book.png'))
pixmap = pixmap.scaled(self.COVER_ICON_SIZE,
self.COVER_ICON_SIZE,
aspectRatioMode=Qt.KeepAspectRatio,
transformMode=Qt.SmoothTransformation)
self.marvin_cover.setPixmap(pixmap)
self.calibre_cover.setMaximumSize(QSize(self.COVER_ICON_SIZE, self.COVER_ICON_SIZE))
self.calibre_cover.setText('')
self.calibre_cover.setScaledContents(False)
self.marvin_cover.setMaximumSize(QSize(self.COVER_ICON_SIZE, self.COVER_ICON_SIZE))
self.marvin_cover.setText('')
self.marvin_cover.setScaledContents(False)
if self.cid:
db = self.opts.gui.current_db
if 'cover_hash' not in self.mismatches:
mi = db.get_metadata(self.cid, index_is_id=True, get_cover=True, cover_as_data=True)
c_image = QImage()
if mi.has_cover:
c_image.loadFromData(mi.cover_data[1])
c_image = c_image.scaledToHeight(self.COVER_ICON_SIZE,
Qt.SmoothTransformation)
self.c_pixmap = QPixmap(QSize(c_image.width(),
c_image.height()))
c_painter = QPainter(self.c_pixmap)
c_painter.setRenderHints(c_painter.Antialiasing)
c_painter.drawImage(0, 0, c_image)
else:
#.........这里部分代码省略.........
示例11: rescale
# 需要导入模块: from PyQt4.Qt import QImage [as 别名]
# 或者: from PyQt4.Qt.QImage import loadFromData [as 别名]
def rescale(self, qt=True):
from calibre.utils.magick.draw import Image
is_image_collection = getattr(self.opts, 'is_image_collection', False)
if is_image_collection:
page_width, page_height = self.opts.dest.comic_screen_size
else:
page_width, page_height = self.opts.dest.width, self.opts.dest.height
page_width -= (self.opts.margin_left + self.opts.margin_right) * self.opts.dest.dpi/72.
page_height -= (self.opts.margin_top + self.opts.margin_bottom) * self.opts.dest.dpi/72.
for item in self.oeb.manifest:
if item.media_type.startswith('image'):
ext = item.media_type.split('/')[-1].upper()
if ext == 'JPG':
ext = 'JPEG'
if ext not in ('PNG', 'JPEG', 'GIF'):
ext = 'JPEG'
raw = item.data
if hasattr(raw, 'xpath') or not raw:
# Probably an svg image
continue
try:
img = Image()
img.load(raw)
except:
continue
width, height = img.size
try:
if self.check_colorspaces and img.colorspace == 'CMYKColorspace':
# We cannot do an imagemagick conversion of CMYK to RGB as
# ImageMagick inverts colors if you just set the colorspace
# to rgb. See for example: https://bugs.launchpad.net/bugs/1246710
from PyQt4.Qt import QImage
from calibre.gui2 import pixmap_to_data
qimg = QImage()
qimg.loadFromData(raw)
if not qimg.isNull():
raw = item.data = pixmap_to_data(qimg, format=ext, quality=95)
img = Image()
img.load(raw)
self.log.warn(
'The image %s is in the CMYK colorspace, converting it '
'to RGB as Adobe Digital Editions cannot display CMYK' % item.href)
else:
self.log.warn(
'The image %s is in the CMYK colorspace, you should convert'
' it to sRGB as Adobe Digital Editions cannot render CMYK' % item.href)
except Exception:
pass
scaled, new_width, new_height = fit_image(width, height,
page_width, page_height)
if scaled:
new_width = max(1, new_width)
new_height = max(1, new_height)
self.log('Rescaling image from %dx%d to %dx%d'%(
width, height, new_width, new_height), item.href)
try:
img.size = (new_width, new_height)
data = img.export(ext.lower())
except KeyboardInterrupt:
raise
except:
self.log.exception('Failed to rescale image')
else:
item.data = data
item.unload_data_from_memory()