def __call__(self, ok): from PyQt4.Qt import QImage, QPainter, QByteArray, QBuffer try: if not ok: raise RuntimeError('Rendering of HTML failed.') de = self.page.mainFrame().documentElement() pe = de.findFirst('parsererror') if not pe.isNull(): raise ParserError(pe.toPlainText()) image = QImage(self.page.viewportSize(), QImage.Format_ARGB32) image.setDotsPerMeterX(96*(100/2.54)) image.setDotsPerMeterY(96*(100/2.54)) painter = QPainter(image) self.page.mainFrame().render(painter) painter.end() ba = QByteArray() buf = QBuffer(ba) buf.open(QBuffer.WriteOnly) image.save(buf, 'JPEG') self.data = str(ba.data()) except Exception as e: self.exception = e self.traceback = traceback.format_exc() finally: self.loop.exit(0)
def add_image(self, img, cache_key): ref = self.get_image(cache_key) if ref is not None: return ref fmt = img.format() image = QImage(img) if (image.depth() == 1 and img.colorTable().size() == 2 and img.colorTable().at(0) == QColor(Qt.black).rgba() and img.colorTable().at(1) == QColor(Qt.white).rgba()): if fmt == QImage.Format_MonoLSB: image = image.convertToFormat(QImage.Format_Mono) fmt = QImage.Format_Mono else: if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32): image = image.convertToFormat(QImage.Format_ARGB32) fmt = QImage.Format_ARGB32 w = image.width() h = image.height() d = image.depth() if fmt == QImage.Format_Mono: bytes_per_line = (w + 7) >> 3 data = image.constBits().asstring(bytes_per_line * h) return self.write_image(data, w, h, d, cache_key=cache_key) has_alpha = False soft_mask = None if fmt == QImage.Format_ARGB32: tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4] sdata = bytearray(tmask) vals = set(sdata) vals.discard(255) # discard opaque pixels has_alpha = bool(vals) if has_alpha: # Blend image onto a white background as otherwise Qt will render # transparent pixels as black background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied) background.fill(Qt.white) painter = QPainter(background) painter.drawImage(0, 0, image) painter.end() image = background ba = QByteArray() buf = QBuffer(ba) image.save(buf, 'jpeg', 94) data = bytes(ba.data()) if has_alpha: soft_mask = self.write_image(tmask, w, h, 8) return self.write_image(data, w, h, 32, dct=True, soft_mask=soft_mask, cache_key=cache_key)
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')
def main(): app = QApplication([]) app tdir = os.path.abspath('.') pdf = os.path.join(tdir, 'painter.pdf') func = full dpi = 100 with open(pdf, 'wb') as f: dev = PdfDevice(f, xdpi=dpi, ydpi=dpi, compress=False) img = QImage(dev.width(), dev.height(), QImage.Format_ARGB32_Premultiplied) img.setDotsPerMeterX(dpi*39.37) img.setDotsPerMeterY(dpi*39.37) img.fill(Qt.white) run(dev, func) run(img, func) path = os.path.join(tdir, 'painter.png') img.save(path) print ('PDF written to:', pdf) print ('Image written to:', path)
def main(): app = QApplication([]) app tdir = os.path.abspath('.') pdf = os.path.join(tdir, 'painter.pdf') func = full dpi = 100 with open(pdf, 'wb') as f: dev = PdfDevice(f, xdpi=dpi, ydpi=dpi, compress=False) img = QImage(dev.width(), dev.height(), QImage.Format_ARGB32_Premultiplied) img.setDotsPerMeterX(dpi * 39.37) img.setDotsPerMeterY(dpi * 39.37) img.fill(Qt.white) run(dev, func) run(img, func) path = os.path.join(tdir, 'painter.png') img.save(path) print('PDF written to:', pdf) print('Image written to:', path)
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")
def render_img(image, dest, width=128, height=128): from PyQt4.Qt import QImage, Qt img = QImage(I(image)).scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) img.save(dest)
def add_image(self, img, cache_key): ref = self.get_image(cache_key) if ref is not None: return ref fmt = img.format() image = QImage(img) if (image.depth() == 1 and img.colorTable().size() == 2 and img.colorTable().at(0) == QColor(Qt.black).rgba() and img.colorTable().at(1) == QColor(Qt.white).rgba()): if fmt == QImage.Format_MonoLSB: image = image.convertToFormat(QImage.Format_Mono) fmt = QImage.Format_Mono else: if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32): image = image.convertToFormat(QImage.Format_ARGB32) fmt = QImage.Format_ARGB32 w = image.width() h = image.height() d = image.depth() if fmt == QImage.Format_Mono: bytes_per_line = (w + 7) >> 3 data = image.constBits().asstring(bytes_per_line * h) return self.write_image(data, w, h, d, cache_key=cache_key) ba = QByteArray() buf = QBuffer(ba) image.save(buf, 'jpeg', 94) data = bytes(ba.data()) has_alpha = has_mask = False soft_mask = mask = None if fmt == QImage.Format_ARGB32: tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4] sdata = bytearray(tmask) vals = set(sdata) vals.discard(255) has_mask = bool(vals) vals.discard(0) has_alpha = bool(vals) if has_alpha: soft_mask = self.write_image(tmask, w, h, 8) elif has_mask: # dither the soft mask to 1bit and add it. This also helps PDF # viewers without transparency support bytes_per_line = (w + 7) >> 3 mdata = bytearray(0 for i in xrange(bytes_per_line * h)) spos = mpos = 0 for y in xrange(h): for x in xrange(w): if sdata[spos]: mdata[mpos + x>>3] |= (0x80 >> (x&7)) spos += 1 mpos += bytes_per_line mdata = bytes(mdata) mask = self.write_image(mdata, w, h, 1) return self.write_image(data, w, h, 32, mask=mask, dct=True, soft_mask=soft_mask, cache_key=cache_key)
import urllib2, sys from PyQt4.Qt import QApplication from PyQt4.Qt import QImage app = QApplication(sys.argv) proxy = urllib2.ProxyHandler({'http': 'sabakgrz:[email protected]:9090'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) # conn = urllib2.urlopen('http://ekskursja.pl/wp-content/plugins/flashcards/flashcards.json.php?name=animal-idioms&id=3652') conn = urllib2.urlopen('http://ekskursja.pl/wp-content/uploads/2014/01/maxresdefault.jpg') data = conn.read() img = QImage() img.loadFromData(data) img.save('test.jpg') # fcjson = conn.read() # c = json.loads(fcjson) # print fc['type']
class Plotter: """ This class communicates with the matplotlib library and plot the data """ def __init__(self, size): """Initialize the plot window, size defines the shape and size of the figure 0 - None, 1 - 8x6, 11 (default) - 12x8, 2 - 2 figs 8x8, 12 - 2 figs 12x8 """ # print('ok') class CustomViewBox(pg.ViewBox): def __init__(self, *args, **kwds): pg.ViewBox.__init__(self, *args, **kwds) self.setMouseMode(self.RectMode) ## reimplement right-click to zoom out def mouseClickEvent(self, ev): if ev.button( ) == QtCore.Qt.RightButton and QtGui.QApplication.keyboardModifiers( ) == QtCore.Qt.ControlModifier: self.autoRange() else: pg.ViewBox.mouseClickEvent(self, ev) def mouseDragEvent(self, ev): mod = QtGui.QApplication.keyboardModifiers() if mod == QtCore.Qt.ControlModifier: self.setMouseMode(self.PanMode) else: self.setMouseMode(self.RectMode) if ev.button() == QtCore.Qt.RightButton: pg.ViewBox.mouseDragEvent(self, ev) else: pg.ViewBox.mouseDragEvent(self, ev) self.vb = CustomViewBox() # not necessary? def clear(self): def ylog(self): """ Change y-scale to log """ vr = self._widget.plotItem.viewRange() xr = vr[0] yr = vr[1] # print(xr,yr) if yr[0] <= 0: yr[0] = 1 yr[0] = np.log10(yr[0]) yr[1] = np.log10(yr[1]) # print(xr,yr) self._widget.plotItem.disableAutoRange() self._widget.plotItem.setLogMode(x=False, y=True) self._widget.plotItem.setRange(xRange=xr, yRange=yr, padding=None) def ylin(self): """ Change y-scale to linear """ vr = self._widget.plotItem.viewRange() xr = vr[0] yr = vr[1] # print(xr,yr) yr[0] = 10**yr[0] yr[1] = 10**yr[1] # print(xr,yr) self._widget.plotItem.disableAutoRange() self._widget.plotItem.setLogMode(x=False, y=False) self._widget.plotItem.setRange(xRange=xr, yRange=yr, padding=None) def plot1d(self, plot, xlim=None, ylim=None): """ Plot 1D histogram The mode defines the way the data are presented, 'histogram' is displayed with steps 'function' with continuus line 'errorbar' with yerrorbars The norm (normalization factor) and bin_size are given for the display purposes only. The histogram is not altered. """ histo = plot.histogram self._widget = PlotWidget(viewBox=self.vb) plt = self._widget.plotItem plt.setTitle(histo.title) plt.plot(histo.x_axis, histo.weights) self._widget.show() # if plot.mode == 'histogram': # current_plot.plot() # win.show() # app.processEvents() def _repr_png_(self): self._widget.hide() QtGui.QApplication.processEvents() try: self.image = QImage(self._widget.viewRect().size().toSize(), QImage.Format_RGB32) except AttributeError: self._widget.updateGL() self.image = self._widget.grabFrameBuffer() painter = QPainter(self.image) self._widget.render(painter) byte_array = QByteArray() buffer = QBuffer(byte_array) buffer.open(QIODevice.ReadWrite) self.image.save(buffer, 'PNG') buffer.close() return bytes(byte_array) def xlim(self, x_range): """ Set x range of plot preserving y limits. """ if x_range == None: yar = self._widget.plotItem.getViewBox().autoRangeEnabled()[1] if yar == False: yr = self._widget.viewRange()[1] else: yr = None # self._widget.plotItem.autoRange() self._widget.plotItem.enableAutoRange() self._widget.plotItem.setAutoVisible(x=True, y=True) if yr != None: self._widget.plotItem.setRange(yRange=yr, padding=None) return None else: if x_range[0] == None: x_range[0] = 0 if x_range[1] == None: self._widget.plotItem.setAutoVisible(x=True, y=False) xr = self._widget.viewRange()[0] x_range[1] = xr[1] self._widget.plotItem.setXRange(x_range[0], x_range[1]) self._widget.plotItem.setAutoVisible(x=False, y=True) def ylim(self, y_range): """ Set y range of plot preserving x limits. """ if y_range == None: xar = self._widget.plotItem.getViewBox().autoRangeEnabled()[0] if xar == False: xr = self._widget.viewRange()[0] else: xr = None self._widget.plotItem.enableAutoRange() self._widget.plotItem.setAutoVisible(x=True, y=True) if xr != None: self._widget.plotItem.setRange(xRange=xr, padding=None) return None else: if y_range[0] == None: y_range[0] = 0 if y_range[1] == None: self._widget.plotItem.setAutoVisible(y=True, x=False) yr = self._widget.viewRange()[1] y_range[1] = yr[1] self._widget.plotItem.setYRange(y_range[0], y_range[1]) self._widget.plotItem.setAutoVisible(y=False, x=True) # def plot1d_4panel(self, plot, ranges): """ Special 1D histogram plot. The plot is broken into 4 panels (stacked verically) the ranges variable should be given in a (x0, x1, x2, x3, x4) format, where xi defines the ranges of the subplots (x0-x1, x1-x2, x2-x3, x3-x4) """ def plot2d(self, plot, xc=None, yc=None, logz=False): """Plot 2D histogram xc is x range, yc is y range """ if plot.histogram.dim != 2: raise GeneralError('plot2d function needs a 2D histogram!') x = plot.histogram.x_axis y = plot.histogram.y_axis w = plot.histogram.weights if xc is not None: x = x[xc[0]:xc[1]] w = w[xc[0]:xc[1], :] if yc is not None: y = y[yc[0]:yc[1]] w = w[:, yc[0]:yc[1]] title = plot.histogram.title # If logaritmic scale is used, mask values <= 0 if logz: w = numpy.ma.masked_where(w <= 0, numpy.log10(w)) title += ' (log10)' self._widget = pg.ImageView(view=pg.PlotItem(title=title)) gv = self._widget.getView() gv.invertY(False) self._widget.setImage(w, pos=[x[0] - 0.5, y[0] - 0.5]) self._widget.show()
def add_image(self, img, cache_key): ref = self.get_image(cache_key) if ref is not None: return ref fmt = img.format() image = QImage(img) if (image.depth() == 1 and img.colorTable().size() == 2 and img.colorTable().at(0) == QColor(Qt.black).rgba() and img.colorTable().at(1) == QColor(Qt.white).rgba()): if fmt == QImage.Format_MonoLSB: image = image.convertToFormat(QImage.Format_Mono) fmt = QImage.Format_Mono else: if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32): image = image.convertToFormat(QImage.Format_ARGB32) fmt = QImage.Format_ARGB32 w = image.width() h = image.height() d = image.depth() if fmt == QImage.Format_Mono: bytes_per_line = (w + 7) >> 3 data = image.constBits().asstring(bytes_per_line * h) return self.write_image(data, w, h, d, cache_key=cache_key) ba = QByteArray() buf = QBuffer(ba) image.save(buf, 'jpeg', 94) data = bytes(ba.data()) has_alpha = has_mask = False soft_mask = mask = None if fmt == QImage.Format_ARGB32: tmask = image.constBits().asstring(4 * w * h)[self.alpha_bit::4] sdata = bytearray(tmask) vals = set(sdata) vals.discard(255) has_mask = bool(vals) vals.discard(0) has_alpha = bool(vals) if has_alpha: soft_mask = self.write_image(tmask, w, h, 8) elif has_mask: # dither the soft mask to 1bit and add it. This also helps PDF # viewers without transparency support bytes_per_line = (w + 7) >> 3 mdata = bytearray(0 for i in xrange(bytes_per_line * h)) spos = mpos = 0 for y in xrange(h): for x in xrange(w): if sdata[spos]: mdata[mpos + x >> 3] |= (0x80 >> (x & 7)) spos += 1 mpos += bytes_per_line mdata = bytes(mdata) mask = self.write_image(mdata, w, h, 1) return self.write_image(data, w, h, 32, mask=mask, dct=True, soft_mask=soft_mask, cache_key=cache_key)
class Plotter: """ This class communicates with the matplotlib library and plot the data """ def __init__(self, size): """Initialize the plot window, size defines the shape and size of the figure 0 - None, 1 - 8x6, 11 (default) - 12x8, 2 - 2 figs 8x8, 12 - 2 figs 12x8 """ # print('ok') class CustomViewBox(pg.ViewBox): def __init__(self, *args, **kwds): pg.ViewBox.__init__(self, *args, **kwds) self.setMouseMode(self.RectMode) ## reimplement right-click to zoom out def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.RightButton and QtGui.QApplication.keyboardModifiers()==QtCore.Qt.ControlModifier: self.autoRange() else: pg.ViewBox.mouseClickEvent(self, ev) def mouseDragEvent(self, ev): mod = QtGui.QApplication.keyboardModifiers() if mod == QtCore.Qt.ControlModifier: self.setMouseMode(self.PanMode) else: self.setMouseMode(self.RectMode) if ev.button() == QtCore.Qt.RightButton: pg.ViewBox.mouseDragEvent(self, ev) else: pg.ViewBox.mouseDragEvent(self, ev) self.vb = CustomViewBox() # not necessary? def clear(self): def ylog(self): """ Change y-scale to log """ vr = self._widget.plotItem.viewRange() xr = vr[0] yr = vr[1] # print(xr,yr) if yr[0]<=0: yr[0]=1 yr[0]=np.log10(yr[0]) yr[1]=np.log10(yr[1]) # print(xr,yr) self._widget.plotItem.disableAutoRange() self._widget.plotItem.setLogMode(x=False, y=True) self._widget.plotItem.setRange(xRange=xr, yRange=yr,padding=None) def ylin(self): """ Change y-scale to linear """ vr = self._widget.plotItem.viewRange() xr = vr[0] yr = vr[1] # print(xr,yr) yr[0]=10**yr[0] yr[1]=10**yr[1] # print(xr,yr) self._widget.plotItem.disableAutoRange() self._widget.plotItem.setLogMode(x=False, y=False) self._widget.plotItem.setRange(xRange=xr, yRange=yr,padding=None) def plot1d(self, plot, xlim=None, ylim=None): """ Plot 1D histogram The mode defines the way the data are presented, 'histogram' is displayed with steps 'function' with continuus line 'errorbar' with yerrorbars The norm (normalization factor) and bin_size are given for the display purposes only. The histogram is not altered. """ histo = plot.histogram self._widget = PlotWidget(viewBox=self.vb) plt = self._widget.plotItem plt.setTitle(histo.title) plt.plot(histo.x_axis, histo.weights) self._widget.show() # if plot.mode == 'histogram': # current_plot.plot() # win.show() # app.processEvents() def _repr_png_(self): self._widget.hide() QtGui.QApplication.processEvents() try: self.image = QImage(self._widget.viewRect().size().toSize(), QImage.Format_RGB32) except AttributeError: self._widget.updateGL() self.image = self._widget.grabFrameBuffer() painter = QPainter(self.image) self._widget.render(painter) byte_array = QByteArray() buffer = QBuffer(byte_array) buffer.open(QIODevice.ReadWrite) self.image.save(buffer, 'PNG') buffer.close() return bytes(byte_array) def xlim(self, x_range): """ Set x range of plot preserving y limits. """ if x_range==None: yar=self._widget.plotItem.getViewBox().autoRangeEnabled()[1] if yar==False: yr=self._widget.viewRange()[1] else: yr=None # self._widget.plotItem.autoRange() self._widget.plotItem.enableAutoRange() self._widget.plotItem.setAutoVisible(x=True,y=True) if yr!=None: self._widget.plotItem.setRange(yRange=yr,padding=None) return None else: if x_range[0]==None: x_range[0]=0 if x_range[1]==None: self._widget.plotItem.setAutoVisible(x=True,y=False) xr=self._widget.viewRange()[0] x_range[1]=xr[1] self._widget.plotItem.setXRange(x_range[0],x_range[1]) self._widget.plotItem.setAutoVisible(x=False,y=True) def ylim(self, y_range): """ Set y range of plot preserving x limits. """ if y_range==None: xar=self._widget.plotItem.getViewBox().autoRangeEnabled()[0] if xar==False: xr=self._widget.viewRange()[0] else: xr=None self._widget.plotItem.enableAutoRange() self._widget.plotItem.setAutoVisible(x=True,y=True) if xr!=None: self._widget.plotItem.setRange(xRange=xr,padding=None) return None else: if y_range[0]==None: y_range[0]=0 if y_range[1]==None: self._widget.plotItem.setAutoVisible(y=True,x=False) yr=self._widget.viewRange()[1] y_range[1]=yr[1] self._widget.plotItem.setYRange(y_range[0],y_range[1]) self._widget.plotItem.setAutoVisible(y=False,x=True) # def plot1d_4panel(self, plot, ranges): """ Special 1D histogram plot. The plot is broken into 4 panels (stacked verically) the ranges variable should be given in a (x0, x1, x2, x3, x4) format, where xi defines the ranges of the subplots (x0-x1, x1-x2, x2-x3, x3-x4) """ def plot2d(self, plot, xc=None, yc=None, logz=False): """Plot 2D histogram xc is x range, yc is y range """ if plot.histogram.dim != 2: raise GeneralError('plot2d function needs a 2D histogram!') x = plot.histogram.x_axis y = plot.histogram.y_axis w = plot.histogram.weights if xc is not None: x = x[xc[0]:xc[1]] w = w[xc[0]:xc[1],:] if yc is not None: y = y[yc[0]:yc[1]] w = w[:, yc[0]:yc[1]] title = plot.histogram.title # If logaritmic scale is used, mask values <= 0 if logz: w = numpy.ma.masked_where(w <= 0, numpy.log10(w)) title += ' (log10)' self._widget = pg.ImageView(view=pg.PlotItem(title=title)) gv = self._widget.getView() gv.invertY(False) self._widget.setImage(w,pos=[x[0]-0.5,y[0]-0.5]) self._widget.show()