class HeroShipView: """ Represents the Graphical view of the Hero's ship """ def __init__(self, ship_model): """ Initialize the ship view """ self.ship_model = ship_model self.scaled_ship = None def loadShipImage(self, width, height): """ Load the ship image """ self.unscaled_ship = QImage("hero_ship.png") matrix = QMatrix() matrix = matrix.rotate(180) self.unscaled_ship = self.unscaled_ship.transformed(matrix) xScaledSize = width*self.ship_model.rectangle.width/100 yScaledSize = height*self.ship_model.rectangle.height/100 self.scaled_ship = self.unscaled_ship.scaled(xScaledSize, yScaledSize) def draw(self, painter, window): """ Draw the image """ if self.scaled_ship is None: self.loadShipImage(window.contentsRect().width(), window.contentsRect().height()) painter.drawImage(self.ship_model.rectangle.x*window.contentsRect().width()/100, self.ship_model.rectangle.y*window.contentsRect().height()/100, self.scaled_ship)
def convert_bitmap(image, width=None, height=None): pix = None if isinstance(image, ImageResource): pix = traitsui_convert_bitmap(image) elif isinstance(image, Image): # image = image.convert('RGBA') data = image.tostring('raw', 'RGBA') im = QImage(data, image.size[0], image.size[1], QImage.Format_ARGB32) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: s = image.shape if len(s) >= 2: # im = QImage(image.tostring(),s[1], s[0], QImage.Format_RGB888) im = QImage(image, s[1], s[0], QImage.Format_RGB888) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: pix = QPixmap() if pix: if width > 0 and height > 0: pix = pix.scaled(width, height) elif width > 0: pix = pix.scaledToWidth(width) if height > 0: pix = pix.scaledToHeight(height) return pix
def __loadCrop(self, loadCrop=True): name_wo_ext = self.__fileNameWoExt() json_data = open(name_wo_ext + '.json').read() image = QImage() if loadCrop: image.load(name_wo_ext + '.crop', 'PNG') return image, json.loads(json_data)
def render(self, fileName, width, height): self.setViewportSize(QSize(width, height)) fileInfo = QFileInfo(fileName) dir = QDir() dir.mkpath(fileInfo.absolutePath()) viewportSize = self.viewportSize() pageSize = self.mainFrame().contentsSize() if pageSize.isEmpty(): return False buffer = QImage(pageSize, QImage.Format_ARGB32) buffer.fill(qRgba(255, 255, 255, 0)) p = QPainter(buffer) p.setRenderHint( QPainter.Antialiasing, True) p.setRenderHint( QPainter.TextAntialiasing, True) p.setRenderHint( QPainter.SmoothPixmapTransform, True) self.setViewportSize(pageSize) self.mainFrame().render(p) p.end() self.setViewportSize(viewportSize) return buffer.save(fileName)
def saveBMC(self): """ .. TODO:: Save a Brother PEL image (An 8bpp, 130x113 pixel monochromatic? bitmap image) Why 8bpp when only 1bpp is needed? .. TODO:: Should BMC be limited to ~32KB or is this a mix up with Bitmap Cache? .. TODO:: Is there/should there be other embedded data in the bitmap besides the image itself? .. NOTE:: Can save a Singer BMC image (An 8bpp, 130x113 pixel colored bitmap image) """ # TODO: figure out how to center the image, right now it just plops it to the left side. img = QImage(150, 150, QImage.Format_ARGB32_Premultiplied) img.fill(qRgb(255, 255, 255)) extents = self.gscene.itemsBoundingRect() # QRectF painter = QPainter(img) targetRect = QRectF(0, 0, 150, 150) if self.mainWin.getSettingsPrintingDisableBG(): # TODO: Make BMC background into it's own setting? brush = self.gscene.backgroundBrush() # QBrush self.gscene.setBackgroundBrush(Qt.NoBrush) self.gscene.update() self.gscene.render(painter, targetRect, extents, Qt.KeepAspectRatio) self.gscene.setBackgroundBrush(brush) else: self.gscene.update() self.gscene.render(painter, targetRect, extents, Qt.KeepAspectRatio) img.convertToFormat(QImage.Format_Indexed8, Qt.ThresholdDither | Qt.AvoidDither).save("test.bmc", "BMP")
def __init__(self, circuit): super(CircuitItem, self).__init__() self.setFlag(QGraphicsItem.ItemIsMovable) self.setFlag(QGraphicsItem.ItemIsSelectable) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges) imgDir = filePath('icons/') self.data = circuit """The real info. The class CircuitItem is just a graphical container around it. data is saved / loaded to / from file. """ self.image = QImage(imgDir + circuit.__class__.__name__ + '.png') """The graphical representation of our item on screen.""" if not self.image: self.image = QImage(imgDir + 'Default.png') self.showCategory = True self.showName = True """Is the item's name shown on screen?""" self.showCategory = False """Is the item's category (circuit class) shown on screen?""" self.name = QGraphicsSimpleTextItem(self) # that won't rotate when the PlugItem is rotated by the user. self.name.setFlag(QGraphicsItem.ItemIgnoresTransformations) self.name.setText(self.data.name) self.category = QGraphicsSimpleTextItem(self) self.category.setFlag(QGraphicsItem.ItemIgnoresTransformations) self.category.setText(self.data.category) self.setupPaint()
def capture(self, region=None, selector=None, format=QImage.Format_ARGB32_Premultiplied): """Returns snapshot as QImage. :param region: An optional tuple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if region is None and selector is not None: region = self.region_for_selector(selector) if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) image = QImage(QSize(x2, y2), format) painter = QPainter(image) self.main_frame.render(painter) painter.end() image = image.copy(x1, y1, w, h) else: self.main_frame.setScrollBarPolicy(QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) self.main_frame.setScrollBarPolicy(QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff) self.page.setViewportSize(self.main_frame.contentsSize()) image = QImage(self.page.viewportSize(), format) painter = QPainter(image) self.main_frame.render(painter) painter.end() return image
def export_color_map(self): name = QtGui.QFileDialog.getSaveFileName(self, 'Export Colormap', filter = IMAGE_SAVE_FILTER)[0] if not name: return color_image = QImage(512, 512, QImage.Format_ARGB32) color_lines = [] height_found = [] for y in xrange(0, 512): color_lines.append(color_image.scanLine(y)) height_found.append([]) for x in xrange(0, 512): height_found[y].append(False) progress = progress_dialog(self.edit_widget, 0, 63, 'Exporting Colormap...') for z in xrange(0, 64): if progress.wasCanceled(): break progress.setValue(z) image = self.layers[z] for y in xrange(0, 512): image_line = image.scanLine(y) color_line = color_lines[y] for x in xrange(0, 512): if height_found[y][x] is False: s = x * 4 image_pixel = image_line[s:s + 4] if image_pixel != TRANSPARENT_PACKED: height_found[y][x] = True color_line[s:s + 4] = image_pixel color_image.save(name)
def export_height_map(self): name = QtGui.QFileDialog.getSaveFileName(self, 'Export Heightmap', filter = IMAGE_SAVE_FILTER)[0] if not name: return height_packed = [] for z in xrange(0, 64): height = (63 - z) * 4 height_packed.append(struct.pack('I', QtGui.qRgba(height, height, height, 255))) height_image = QImage(512, 512, QImage.Format_ARGB32) height_lines = [] height_found = [] for y in xrange(0, 512): height_lines.append(height_image.scanLine(y)) height_found.append([]) for x in xrange(0, 512): height_found[y].append(False) progress = progress_dialog(self.edit_widget, 0, 63, 'Exporting Heightmap...') for z in xrange(0, 64): if progress.wasCanceled(): break progress.setValue(z) packed_value = height_packed[z] image = self.layers[z] for y in xrange(0, 512): image_line = image.scanLine(y) height_line = height_lines[y] for x in xrange(0, 512): if height_found[y][x] is False: s = x * 4 if image_line[s:s + 4] != TRANSPARENT_PACKED: height_found[y][x] = True height_line[s:s + 4] = packed_value height_image.save(name)
def set_clipboard_image(self): """Export the formatted output to an image and store it in the clipboard. The image stored in the clipboard is a PNG file with alpha transparency. """ div = self.view.page().mainFrame().findFirstElement('.output') images = {} for background in (Qt.transparent, Qt.white): image = QImage(div.geometry().size(), QImage.Format_ARGB32_Premultiplied) image.fill(background) painter = QPainter(image) div.render(painter) painter.end() images[background] = image # Windows needs this buffer hack to get alpha transparency in # the copied PNG. buffer_ = QBuffer() buffer_.open(QIODevice.WriteOnly) images[Qt.transparent].save(buffer_, 'PNG') buffer_.close() data = QMimeData() data.setData('PNG', buffer_.data()) data.setImageData(images[Qt.white]) QApplication.clipboard().setMimeData(data)
def copy_to_clipboard(plot): # pass # @staticmethod # def wx_copy_to_clipboard(plot): # # WX specific, though QT implementation is similar using # # QImage and QClipboard # import wx # width, height = plot.outer_bounds # gc = PlotGraphicsContext((width, height), dpi=72) backbuffer = plot.use_backbuffer plot.use_backbuffer = False gc.render_component(plot) plot.use_backbuffer = backbuffer # # # Create a bitmap the same size as the plot # # and copy the plot data to it bmp = gc.bmp_array if gc.format().startswith('bgra'): bmp_rgba = bmp[:,:,[2,1,0,3]] else: bmp_rgba = bmp bitmap=QImage(bmp_rgba.tostring(),width,height, PySide.QtGui.QImage.Format_RGB32) if QApplication.clipboard(): QApplication.clipboard().setImage(bitmap.copy()) else: PySide.QtGui.QMessageBox("Unable to open the clipboard.", "Error")
def paint(self, painter, option, widget=None): painter_inverted = QPainter() brect= QGraphicsProxyWidget.boundingRect(self) invertedColor = QImage(brect.width(),brect.height(),QImage.Format_RGB32) painter_inverted.begin(invertedColor) QGraphicsProxyWidget.paint(self,painter_inverted, option, widget) painter_inverted.end() painter.drawImage(0,0,invertedColor.rgbSwapped())
def LoadImage(imageFilename, scaledXSize=None, scaledYSize=None): """ Loads the Image and scales it if necessary """ unscaled_image = QImage(imageFilename) if scaledXSize is not None and scaledYSize is not None: return unscaled_image.scaled(scaledXSize, scaledYSize) else: return unscaled_image
def rotateImage(self,filepath): print "ROTATING FILE: " + filepath img = QImage(filepath) rot = QTransform() rot = rot.rotate(90) img = img.transformed(rot) img.save(filepath) self.imageRotated.emit(filepath)
def SetImageTransparency(image, transparencyPercentage): """ Set the Image Transparency to the value provided """ alpha = QImage(image) painter = QPainter(alpha) alphaValue = int(transparencyPercentage*255/100) painter.fillRect(alpha.rect(), QColor(alphaValue, alphaValue, alphaValue)) painter.end() image.setAlphaChannel(alpha)
def capture(self, filename): image = QImage(self._view.page().currentFrame().contentsSize(), QImage.Format_ARGB32) painter = QPainter(image) self._view.page().currentFrame().render(painter) painter.end() image.save(filename)
def resizeImage(self, image, newSize): if image.size() == newSize: return newImage = QImage(newSize, QImage.Format_RGB32) newImage.fill(qRgb(255, 255, 255)) painter = QPainter(newImage) painter.drawImage(QtCore.QPoint(0, 0), image) self.image = newImage
def drawIconWithShadow(icon, rect, p, iconMode, radius, color, offset): cache = QPixmap() pixmapName = "icon {0} {1} {2}".format(icon.cacheKey(), iconMode, rect.height()) if not QPixmapCache.find(pixmapName, cache): px = icon.pixmap(rect.size()) cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cachePainter = QPainter(cache) if iconMode == QIcon.Disabled: im = px.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(im.height()): scanLine = im.scanLine(y) for x in range(im.width()): pixel = scanLine intensity = qGray(pixel) scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel)) scanLine += 1 px = QPixmap.fromImage(im) # Draw shadow tmp = QImage(px.size() + QSize(radius * 2, radius * 2 + 1), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmpPainter = QPainter(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_Source) tmpPainter.drawPixmap(QPoint(radius, radius), px) tmpPainter.end() # blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blurred.fill(Qt.transparent) blurPainter = QPainter(blurred) # todo : blur image blurPainter.end() tmp = blurred # blacken the image tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() # draw the blurred drop shadow... cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap... cachePainter.drawPixmap(QPoint(radius, radius) + offset, px) QPixmapCache.insert(pixmapName, cache) targetRect = cache.rect() targetRect.moveCenter(rect.center()) p.drawPixmap(targetRect.topLeft() - offset, cache)
def __init__(self, svgImage, width, height, parent=None): super(SvgButton, self).__init__(parent) svg_renderer = QSvgRenderer(svgImage) image = QImage(width, height, QImage.Format_ARGB32) # Set the ARGB to 0 to prevent rendering artifacts image.fill(0x00000000) svg_renderer.render(QPainter(image)) pixmap = QPixmap.fromImage(image) icon = QIcon(pixmap) self.setIcon(icon) self.setIconSize(QSize(width, height))
def __init__(self, parent=None): super(PaintArea, self).__init__(parent) self.autoFillBackground = True self.myPenWidth = 3 self.myPenColor = QColor(100, 100, 100, 255) self.size_w = 500 self.size_h = 500 imageSize = QtCore.QSize(self.size_w, self.size_h) self.image = QImage(imageSize, QImage.Format_RGB32) self.imagePreview = QImage(imageSize, QImage.Format_ARGB32) self.lastPoint = QtCore.QPoint() self.setMinimumSize(imageSize) self.setMaximumSize(imageSize)
def __init__(self, directory, filename): self.directory = directory self.filename = filename image = QImage(self.directory + QDir.separator() + self.filename) Rect.__init__(self, Point(), Size(image.width(), image.height())) cropped_image, x, y, width, height = self.__getCrop(image, False) self.crop = Rect(Point(x, y), Size(width, height)) self.rotated = False
def create_red_image(self, img): new_img = QImage(img) for x in range(0, img.width()): for y in range(0, img.height()): pix = img.pixel(x, y) r = pix & 0xFF g = (pix >> 8) & 0xFF b = (pix >> 16) & 0xFF alpha_mask = pix & 0xFF000000 new_img.setPixel(x, y, (alpha_mask | ((r + g + b) / 3))) return new_img
def takeScreenshot(self): [x,y,width,height] = self.image_crop frame = self.page().mainFrame() size = frame.contentsSize() size.setWidth(1000) size.setHeight(2000) self.page().setViewportSize(size) image = QImage(self.page().viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() image1 = image.copy(x,y,width,height) image1.save(self.fileName) self.finished = True
def qimage_of_bgr(bgr): """ A QImage representation of a BGR numpy array """ bgr = cv2.cvtColor(bgr.astype('uint8'), cv2.COLOR_BGR2RGB) bgr = np.ascontiguousarray(bgr) qt_image = QImage(bgr.data, bgr.shape[1], bgr.shape[0], bgr.strides[0], QImage.Format_RGB888) # QImage does not take a deep copy of np_arr.data so hold a reference # to it assert(not hasattr(qt_image, 'bgr_array')) qt_image.bgr_array = bgr return qt_image
def updateContact(self,jid): #if "@g.us" in jid: # user_img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/group.png") #else: # user_img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/user.png") jname = jid.replace("@s.whatsapp.net","").replace("@g.us","") if os.path.isfile(WAConstants.CACHE_CONTACTS + "/" + jname + ".jpg"): user_img = QImage(WAConstants.CACHE_CONTACTS + "/" + jname + ".jpg") user_img.save(WAConstants.CACHE_PROFILE + "/" + jname + ".jpg", "JPEG") self.imageProcessor.createSquircle(WAConstants.CACHE_CONTACTS + "/" + jname + ".jpg", WAConstants.CACHE_CONTACTS + "/" + jname + ".png") self.contactPictureUpdated.emit(jid);
class RatingDelegate(NoFocusDelegate): """ Star Rating Item Delegate Model View Delegate which draws a rating score between zero and five as a line of zero to five star glyphs. A custom star glyph can be passed to the constructor, otherwise a resource named '/icons/star.png' is used. See also RatingEditor. """ # TODO: Create RatingEditor and link here def __init__(self, parent=None, star=None): super(RatingDelegate, self).__init__(parent) if star is None: self._star = QImage(":/icons/star.png") elif not isinstance(star, QImage): raise TypeError("Star Image must be a descendant of QImage") else: self._star = star def paint(self, p, option, index): p.save() self.drawBackground(p, option, index) rating = index.data() width = self._star.width() y = (option.rect.height() - self._star.height()) / 2 p.translate(option.rect.left(), option.rect.top()) for i in range(0, 5): if rating >= (i + 1): p.drawImage(i * (width + 1), y, self._star) p.restore() def sizeHint(self, option, index): return QSize((self._star.width() + 2) * 5, self._star.height() + 2) def setStarImage(self, star): "Set the Star Image" if not isinstance(star, QImage): raise TypeError("Star Image must be a descendant of QImage") self._star = star def starImage(self): return self._star
def end_adding(self, gl): self.texture.bind(gl) ''' IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT The image has to be mirrored for some reason ''' img = QImage(self.bitmap.toImage()).mirrored() img = QGLWidget.convertToGLFormat(img) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width(), img.height(), 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, str(img.bits())) # This particular bitmap is no longer needed self.bitmap = None
def loadBackgroundImage(self, width, height): """ Load the ship image """ xScaledSize = width yScaledSize = height self.unscaled_background = QImage("Space_Background_bigger.gif") self.scaled_background = self.unscaled_background.scaled(xScaledSize, yScaledSize)
def test_fire_png(self): fire = QImage("data/fire.png") cropper = CropTransparent(fire.width(), fire.height(), 50, str(fire.constBits())) self.assertEqual(cropper.getCroppedOffsetX(), 16) self.assertEqual(cropper.getCroppedOffsetY(), 15) self.assertEqual(cropper.getCroppedHeight(), 226) self.assertEqual(cropper.getCroppedWidth(), 226) crop_rect = cropper.getRect() self.assertEqual(crop_rect.x, 16) self.assertEqual(crop_rect.y, 15) self.assertEqual(crop_rect.width, 226) self.assertEqual(crop_rect.height, 226)
class Country(object): ''' ISO 3166 Country Class Holds information about a Country including its name, ISO 3166 code, and a Qt Image of the country flag, if the resource is available. The flag image should reside in the resource /flags/xx.png, where xx is the two- character lower-case country code. ''' def __init__(self, code): self.code = code.upper() self._flag = None self._icon = None def __unicode__(self): return unicode(self.code or u'') def __eq__(self, other): return unicode(self) == unicode(other) def __ne__(self, other): return not self.__eq__(other) def __cmp__(self, other): return cmp(unicode(self), unicode(other)) def __hash__(self): return hash(unicode(self)) def __repr__(self): return "%s(code=%r)" % (self.__class__.__name__, unicode(self)) def __nonzero__(self): return bool(self.code) def __len__(self): return len(unicode(self)) @property def name(self): # Local import so the countries aren't loaded unless they are needed. from countries import COUNTRIES for code, name in COUNTRIES: if self.code.upper() == code.upper(): return name return '' @property def flag(self): # Load flag image from resource if not self._flag: from PySide.QtGui import QImage self._flag = QImage(':/flags/%s.png' % self.code.lower()) return self._flag if not self._flag.isNull() else None @property def icon(self): # Load flag icon from resource from PySide.QtGui import QIcon return QIcon(':/flags/%s.png' % self.code.lower())
def svg2icon(path, img_type=QImage): img = QImage(64, 64, QImage.Format_ARGB32) svgrenderer = QSvgRenderer(path) paint = QPainter(img) paint.setRenderHint(QPainter.HighQualityAntialiasing) paint.setRenderHint(QPainter.SmoothPixmapTransform) paint.setBrush(QColor(255, 255, 255, 255)) paint.drawRect(QRect(-1, -1, 65, 65)) svgrenderer.render(paint) paint.end() if img_type == QImage: return img elif img_type == QPixmap: pix = QPixmap pix = pix.fromImage(img) return pix
def __init__(self, *args): super(CheckBox, self).__init__(*args) self.setMouseTracking(True) if tuple() in [type(i) for i in args]: for arg in args: if isinstance(arg) == tuple(): color = arg else: color = (QColor(0, 150, 136), QColor(255, 255, 255)) self.color1 = color[0] self.color2 = color[1] self.svgrenderer = QSvgRenderer("icons\\check.svg") self.check = QImage(500, 200, QImage.Format_ARGB32) self.resize(30, 30) paint = QPainter(self.check) self.svgrenderer.render(paint) paint.end()