Ejemplo n.º 1
1
def convertToGray(image):
    grayImg = QImage(image.size(), QImage.Format_ARGB32)
    for i in range(image.width()):
        for j in range(image.height()):
            rgb = image.pixel(i, j)
            gray = qGray(rgb)
            alpha = qAlpha(rgb)
            grayPixel = qRgba(gray, gray, gray, alpha)
            grayImg.setPixel(i, j, grayPixel)
    return grayImg
Ejemplo n.º 2
0
    def resizeEvent(self, event):
        #When the widget is resized, we need to update the alpha channel.
        self.alphaChannel = QImage(self.size(),
                                   QImage.Format_ARGB32_Premultiplied)
        self.buffer = QImage(self.size(), QImage.Format_ARGB32_Premultiplied)

        #Create Alpha Channel:
        if self.width() > 64:
            #create first scanline
            scanline = [0] * self.width()
            for x in range(0, 15):
                scanline[x] = scanline[self.width() - x - 1] = qRgba(
                    0, 0, 0, x << 4)
            # Background
            for x in range(15, self.width() - 15):
                scanline[x] = qRgb(0, 0, 0)
            #copy scanline to the other ones
            for y in range(0, self.height()):
                for x in range(0, self.width()):
                    self.alphaChannel.setPixel(x, y, scanline[x])
        else:
            self.alphaChannel.fill(qRgba(0, 0, 0, 0))

        #Update scrolling state
        newScrollEnabled = (self.singleTextWidth >
                            self.width() - self.leftMargin)
        if newScrollEnabled != self.scrollEnabled:
            self.updateText()
Ejemplo n.º 3
0
    def set_colors(data: bin,
                   fg: QColor,
                   bg: QColor,
                   trans: QColor,
                   swap_fg_bg=False) -> bin:  # pylint: disable=too-many-locals
        """
        Burns foreground and background colors into a raster image, and returns
        the results as a PNG binary
        """
        image = QImage()
        image.loadFromData(data)
        if image.isNull():
            raise UnreadablePictureException(
                'Could not read embedded picture data')

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        fg_rgba = qRgba(fg.red(), fg.green(), fg.blue(),
                        fg.alpha()) if fg and fg.isValid() else None
        bg_rgba = qRgba(bg.red(), bg.green(), bg.blue(),
                        bg.alpha()) if bg and bg.isValid() else None

        COLOR_TOLERANCE = 40

        fg_comp = 0
        bg_comp = 255

        for y in range(image.height()):
            start = y * image.width() * 4
            for x in range(image.width()):
                x_start = x * 4 + start
                rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]
                if trans and abs(qRed(rgba) - trans.red(
                )) < COLOR_TOLERANCE and abs(qGreen(rgba) - trans.green(
                )) < COLOR_TOLERANCE and abs(qBlue(rgba) -
                                             trans.blue()) < COLOR_TOLERANCE:
                    ucharptr[x_start:x_start + 4] = struct.pack(
                        'I', qRgba(0, 0, 0, 0))
                elif fg_rgba is not None and abs(
                        qRed(rgba) - fg_comp) < COLOR_TOLERANCE and abs(
                            qGreen(rgba) - fg_comp) < COLOR_TOLERANCE and abs(
                                qBlue(rgba) - fg_comp) < COLOR_TOLERANCE:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', fg_rgba)
                elif bg_rgba is not None and abs(
                        qRed(rgba) - bg_comp) < COLOR_TOLERANCE and abs(
                            qGreen(rgba) - bg_comp) < COLOR_TOLERANCE and abs(
                                qBlue(rgba) - bg_comp) < COLOR_TOLERANCE:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', bg_rgba)

        # convert to PNG
        png_data = QBuffer()
        image.save(png_data, "png")
        return png_data.data()
Ejemplo n.º 4
0
def _maskCvt(source, idx: int):
    if not source.loaded:
        return QPixmap()
    data = source._imageAt(idx)
    mask = make_lung_mask(data)
    image = QImage(*data.shape[::-1], QImage.Format_ARGB32)
    image.fill(qRgba(0, 0, 0, 255)) # black background
    pixel = qRgba(0, 0, 0, 0) # transparent background
    for (row, col) in np.transpose(np.nonzero(mask)):
        image.setPixel(col.item(), row.item(), pixel)
    return QPixmap.fromImage(image)
Ejemplo n.º 5
0
    def colorize_picture(picture, color):
        """
        Applies a color overlay to a picture, emulating the ArcMap
        results
        """
        if issubclass(picture.__class__, StdPicture):
            picture = picture.picture

        image = QImage()
        image.loadFromData(picture.content)
        if image.isNull():
            raise UnreadablePictureException('Could not read embedded picture data')

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        # assume top left pixel is transparent?
        c = image.pixelColor(0, 0)
        trans_rgba = qRgba(c.red(), c.green(), c.blue(), c.alpha())
        actual_trans_rgba = qRgba(c.red(), c.green(), c.blue(), 0)

        for y in range(image.height()):
            start = y * image.width() * 4
            for x in range(image.width()):
                x_start = x * 4 + start
                rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]

                if rgba == trans_rgba:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', actual_trans_rgba)

        if color is None or color.is_null:
            return image

        fg_color = ColorConverter.color_to_qcolor(color)
        if not fg_color.isValid():
            return image

        alpha = QImage(image)
        image.detach()
        p = QPainter(image)
        p.setCompositionMode(QPainter.CompositionMode_SourceIn)
        p.setBrush(fg_color)
        p.drawRect(image.rect())
        p.setCompositionMode(QPainter.CompositionMode_Multiply)
        p.drawImage(0, 0, alpha)
        p.end()
        return image
Ejemplo n.º 6
0
    def __init__(self, text, parent):
        super(DragLabel, self).__init__(parent)

        metric = QFontMetrics(self.font())
        size = metric.size(Qt.TextSingleLine, text)

        image = QImage(size.width() + 12, size.height() + 12, QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(0, 0, 0, 0))

        font = QFont()
        font.setStyleStrategy(QFont.ForceOutline)

        painter = QPainter()
        painter.begin(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.drawRoundedRect(QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, Qt.RelativeSize)

        painter.setFont(font)
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter, text)
        painter.end()

        self.setPixmap(QPixmap.fromImage(image))
        self.labelText = text
Ejemplo n.º 7
0
    def paintEvent(self, event):
        p = QPainter(self)

        if self.scrollEnabled:
            self.buffer.fill(qRgba(0, 0, 0, 0))
            pb = QPainter(self.buffer)
            pb.setPen(p.pen())
            pb.setFont(p.font())

            x = min(-self.scrollPos, 0) + self.leftMargin
            while x < self.width():
                pb.drawStaticText(
                    QPointF(x,
                            (self.height() - self.wholeTextSize.height()) / 2)
                    + QPoint(2, 2), self.staticText)
                x += self.wholeTextSize.width()

            #Apply Alpha Channel
            pb.setCompositionMode(QPainter.CompositionMode_DestinationIn)
            pb.setClipRect(self.width() - 15, 0, 15, self.height())
            pb.drawImage(0, 0, self.alphaChannel)
            pb.setClipRect(0, 0, 15, self.height())
            #initial situation: don't apply alpha channel in the left half of the image at all; apply it more and more until scrollPos gets positive
            if self.scrollPos < 0:
                pb.setOpacity((max(-8, self.scrollPos) + 8) / 8.0)
            pb.drawImage(0, 0, self.alphaChannel)

            p.drawImage(0, 0, self.buffer)
        else:
            x = (self.width() - self.wholeTextSize.width()) / 2
            y = (self.height() - self.wholeTextSize.height()) / 2
            p.drawStaticText(QPointF(x, y), self.staticText)
Ejemplo n.º 8
0
 def __init__(self, parent=None):
     super(ScribbleArea, self).__init__(parent)
     self.tempDrawing = False
     self.setMouseTracking(True)
     self.firstPoint = None
     self.secondPoint = None
     self.thirdPoint = None
     self.rectPoint1 = None
     self.rectPoint2 = None
     self.contourPoints = []
     self.overLayed = {}
     self.setAttribute(Qt.WA_StaticContents)
     self.modified = False
     self.clicked = False
     self.state = {}
     self.stateUpdate({'init': False, 'iteration': 0})
     self.myPenWidth = 5
     self.myPenColor = Qt.blue
     self.image = QImage().convertToFormat(5)
     self.image.fill(qRgba(255, 0, 0, 0))
     self.imagePath = None
     self.lastPoint = QPoint()
     self.imagePainter = None
     self.edges = None
     self.app = None
Ejemplo n.º 9
0
    def populate(self):
        self.frames = {}
        for line in self.index:
            x, y = tuple([int(i) for i in line[1].split(',')])
            width, height = tuple([int(i) for i in line[2].split(',')])
            offset = tuple([int(i) for i in line[3].split(',')])
            crop = self.image.copy(x, y, width, height)

            qCOLORKEY = qRgb(*COLORKEY)
            new_color = qRgba(0, 0, 0, 0)
            for x in range(crop.width()):
                for y in range(crop.height()):
                    if crop.pixel(x, y) == qCOLORKEY:
                        crop.setPixel(x, y, new_color)

            print(crop.width(), crop.height(), offset)
            self.frames[line[0]] = (crop, offset)

        self.poses = {}
        self.current_pose = None
        for line in self.script:
            if line[0] == 'pose':
                self.current_pose = line[1]
                self.poses[self.current_pose] = []
            else:
                self.poses[self.current_pose].append(line)
Ejemplo n.º 10
0
    def __init__(self, text, parent):
        super(DragLabel, self).__init__(parent)

        metric = QFontMetrics(self.font())
        size = metric.size(Qt.TextSingleLine, text)

        image = QImage(size.width() + 12,
                       size.height() + 12, QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(0, 0, 0, 0))

        font = QFont()
        font.setStyleStrategy(QFont.ForceOutline)

        painter = QPainter()
        painter.begin(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.drawRoundedRect(
            QRectF(0.5, 0.5,
                   image.width() - 1,
                   image.height() - 1), 25, 25, Qt.RelativeSize)

        painter.setFont(font)
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter, text)
        painter.end()

        self.setPixmap(QPixmap.fromImage(image))
        self.labelText = text
Ejemplo n.º 11
0
    def setPixmap(self, pixmap):
        if pixmap is None:
            qimg = QImage(self.THUMB_SIZE, self.THUMB_SIZE,
                          QImage.Format_ARGB32)
            qimg.fill(qRgba(40, 40, 40, 255))
            self.pixmap = QPixmap.fromImage(qimg)
        else:
            self.pixmap = pixmap

        self.imgwidth = self.pixmap.width()
        self.imgheight = self.pixmap.height()
        self.pixmapitem.setPixmap(self.pixmap)
        self.setSceneRect(QRectF(self.pixmap.rect()))

        if self.imgwidth > self.imgheight:

            aspectratio = self.imgheight / self.imgwidth
            h = (int)(aspectratio * self.width())
            self.setFixedHeight(h)

        # calculate zoom factor
        pixels_of_border = 10
        zf1 = (self.geometry().width() - pixels_of_border) / self.imgwidth
        zf2 = (self.geometry().height() - pixels_of_border) / self.imgheight

        zf = min(zf1, zf2)
        if zf > 1.0:
            zf = 1.0

        self.zoom_factor = zf

        self.updateViewer()
Ejemplo n.º 12
0
 def grayScale(self):
     """
     Public slot to convert the image to gray preserving transparency.
     """
     cmd = IconEditCommand(self, self.tr("Convert to Grayscale"),
                           self.__image)
     for x in range(self.__image.width()):
         for y in range(self.__image.height()):
             col = self.__image.pixel(x, y)
             if col != qRgba(0, 0, 0, 0):
                 gray = qGray(col)
                 self.__image.setPixel(
                     x, y, qRgba(gray, gray, gray, qAlpha(col)))
     self.update()
     self.setDirty(True)
     self.__undoStack.push(cmd)
     cmd.setAfterImage(self.__image)
Ejemplo n.º 13
0
 def grayScale(self, image):
     for i in range(self.w):
         for j in range(self.h):
             c = image.pixel(i, j)
             gray = qGray(c)
             alpha = qAlpha(c)
             image.setPixel(i, j, qRgba(gray, gray, gray, alpha))
     return image
Ejemplo n.º 14
0
 def grayScale(self):
     """
     Public slot to convert the image to gray preserving transparency.
     """
     cmd = IconEditCommand(self, self.tr("Convert to Grayscale"),
                           self.__image)
     for x in range(self.__image.width()):
         for y in range(self.__image.height()):
             col = self.__image.pixel(x, y)
             if col != qRgba(0, 0, 0, 0):
                 gray = qGray(col)
                 self.__image.setPixel(x, y,
                                       qRgba(gray, gray, gray, qAlpha(col)))
     self.update()
     self.setDirty(True)
     self.__undoStack.push(cmd)
     cmd.setAfterImage(self.__image)
Ejemplo n.º 15
0
 def pixmap(self, size, mode, state):
     img = QImage(size, QImage.Format_ARGB32)
     img.fill(qRgba(0, 0, 0, 0))
     pix = QPixmap.fromImage(img, Qt.NoFormatConversion)
     painter = QPainter(pix)
     r = QRect(QPoint(0.0, 0.0), size)
     self.paint(painter, r, mode, state)
     return pix
Ejemplo n.º 16
0
def disabledSideBarIcon(enabledicon: QPixmap) -> QPixmap:
    im = enabledicon.toImage().convertToFormat(QImage.Format_ARGB32)
    for y in range(im.height()):
        for x in range(im.width()):
            pixel = im.pixel(x, y)
            intensity = qGray(pixel)
            im.setPixel(x, y,
                        qRgba(intensity, intensity, intensity, qAlpha(pixel)))
    return QPixmap.fromImage(im)
Ejemplo n.º 17
0
def toGray(image):
    w, h = (image.width(), image.height())
    for x in xrange(w):
        for y in xrange(h):
            pixel = image.pixel(x, y)
            gray = qGray(pixel)
            alpha = qAlpha(pixel)
            image.setPixel(x, y, qRgba(gray, gray, gray, alpha))
    return image
Ejemplo n.º 18
0
    def createQPixmapFromMask(self):

        w = self.bbox[2]
        h = self.bbox[3]
        self.qimg_mask = QImage(w, h, QImage.Format_ARGB32)
        self.qimg_mask.fill(qRgba(0, 0, 0, 0))

        if self.class_name == "Empty":
            rgba = qRgba(255, 255, 255, 255)
        else:
            rgba = qRgba(self.class_color[0], self.class_color[1], self.class_color[2], 100)

        blob_mask = self.getMask()
        for x in range(w):
            for y in range(h):
                if blob_mask[y, x] == 1:
                    self.qimg_mask.setPixel(x, y, rgba)

        self.pxmap_mask = QPixmap.fromImage(self.qimg_mask)
Ejemplo n.º 19
0
    def colorize_picture_data(data, color: QColor, fix_alpha=True):
        """
        Colorizes picture data
        """
        image = QImage()
        image.loadFromData(data)
        if image.isNull():
            raise UnreadablePictureException('Could not read embedded picture data')

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        # assume top left pixel is transparent?
        if fix_alpha:
            c = image.pixelColor(0, 0)
            trans_rgba = qRgba(c.red(), c.green(), c.blue(), c.alpha())
            actual_trans_rgba = qRgba(c.red(), c.green(), c.blue(), 0)

            for y in range(image.height()):
                start = y * image.width() * 4
                for x in range(image.width()):
                    x_start = x * 4 + start
                    rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]

                    if rgba == trans_rgba:
                        ucharptr[x_start:x_start + 4] = struct.pack('I', actual_trans_rgba)

        if not color.isValid():
            return image

        alpha = QImage(image)
        image.detach()
        p = QPainter(image)
        p.setCompositionMode(QPainter.CompositionMode_SourceIn)
        p.setBrush(color)
        p.drawRect(image.rect())
        p.setCompositionMode(QPainter.CompositionMode_Multiply)
        p.drawImage(0, 0, alpha)
        p.end()
        return image
Ejemplo n.º 20
0
 def editNew(self):
     """
     Public slot to generate a new, empty image.
     """
     from .IconSizeDialog import IconSizeDialog
     dlg = IconSizeDialog(self.__image.width(), self.__image.height())
     res = dlg.exec_()
     if res == QDialog.Accepted:
         width, height = dlg.getData()
         img = QImage(width, height, QImage.Format_ARGB32)
         img.fill(qRgba(0, 0, 0, 0))
         self.setIconImage(img)
Ejemplo n.º 21
0
 def editClear(self):
     """
     Public slot to clear the image.
     """
     self.__unMark()
     
     cmd = IconEditCommand(self, self.tr("Clear Image"), self.__image)
     self.__image.fill(qRgba(0, 0, 0, 0))
     self.update()
     self.setDirty(True)
     self.__undoStack.push(cmd)
     cmd.setAfterImage(self.__image)
Ejemplo n.º 22
0
    def pixelcode_2x2(self, img):
        result = QImage(img.width()*2, img.height()*2, QImage.Format_ARGB32 )
        white = qRgba(255,255,255,0)
        black = qRgba(0,0,0,255)

        for x in range(img.width()):
            for y in range(img.height()):
                c = img.pixel(QPoint(x,y))
                colors = QColor(c).getRgbF()
                if colors[0]:
                    result.setPixel(x*2+1,y*2+1, black)
                    result.setPixel(x*2,y*2+1, white)
                    result.setPixel(x*2+1,y*2, white)
                    result.setPixel(x*2, y*2, black)

                else:
                    result.setPixel(x*2+1,y*2+1, white)
                    result.setPixel(x*2,y*2+1, black)
                    result.setPixel(x*2+1,y*2, black)
                    result.setPixel(x*2, y*2, white)
        return result
Ejemplo n.º 23
0
    def editClear(self):
        """
        Public slot to clear the image.
        """
        self.__unMark()

        cmd = IconEditCommand(self, self.tr("Clear Image"), self.__image)
        self.__image.fill(qRgba(0, 0, 0, 0))
        self.update()
        self.setDirty(True)
        self.__undoStack.push(cmd)
        cmd.setAfterImage(self.__image)
Ejemplo n.º 24
0
    def pixelcode_2x2(self, img):
        result = QImage(img.width()*2, img.height()*2, QImage.Format_ARGB32 )
        white = qRgba(255,255,255,0)
        black = qRgba(0,0,0,255)

        for x in range(img.width()):
            for y in range(img.height()):
                c = img.pixel(QPoint(x,y))
                colors = QColor(c).getRgbF()
                if colors[0]:
                    result.setPixel(x*2+1,y*2+1, black)
                    result.setPixel(x*2,y*2+1, white)
                    result.setPixel(x*2+1,y*2, white)
                    result.setPixel(x*2, y*2, black)

                else:
                    result.setPixel(x*2+1,y*2+1, white)
                    result.setPixel(x*2,y*2+1, black)
                    result.setPixel(x*2+1,y*2, black)
                    result.setPixel(x*2, y*2, white)
        return result
Ejemplo n.º 25
0
 def editNew(self):
     """
     Public slot to generate a new, empty image.
     """
     from .IconSizeDialog import IconSizeDialog
     dlg = IconSizeDialog(self.__image.width(), self.__image.height())
     res = dlg.exec_()
     if res == QDialog.Accepted:
         width, height = dlg.getData()
         img = QImage(width, height, QImage.Format_ARGB32)
         img.fill(qRgba(0, 0, 0, 0))
         self.setIconImage(img)
Ejemplo n.º 26
0
def adjustBright(image: QImage, value) -> QImage:
    width, height = image.width(), image.height()
    newImage = QImage(width, height, QImage.Format_RGBA8888)
    for h in range(height):
        for w in range(width):
            pixel = QColor(image.pixel(h, w))
            red = (pixel.red() + value)
            red = bound(0, 255, red)
            green = (pixel.green() + value)
            green = bound(0, 255, green)
            blue = (pixel.blue() + value)
            blue = bound(0, 255, blue)
            newImage.setPixel(h, w, qRgba(red, green, blue, pixel.alpha()))
    return newImage
Ejemplo n.º 27
0
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget (QWidget)
        """
        super(IconEditorGrid, self).__init__(parent)

        self.setAttribute(Qt.WA_StaticContents)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self.__curColor = Qt.black
        self.__zoom = 12
        self.__curTool = self.Pencil
        self.__startPos = QPoint()
        self.__endPos = QPoint()
        self.__dirty = False
        self.__selecting = False
        self.__selRect = QRect()
        self.__isPasting = False
        self.__clipboardSize = QSize()
        self.__pasteRect = QRect()

        self.__undoStack = QUndoStack(self)
        self.__currentUndoCmd = None

        self.__image = QImage(32, 32, QImage.Format_ARGB32)
        self.__image.fill(qRgba(0, 0, 0, 0))
        self.__markImage = QImage(self.__image)
        self.__markImage.fill(self.NoMarkColor.rgba())

        self.__compositingMode = QPainter.CompositionMode_SourceOver
        self.__lastPos = (-1, -1)

        self.__gridEnabled = True
        self.__selectionAvailable = False

        self.__initCursors()
        self.__initUndoTexts()

        self.setMouseTracking(True)

        self.__undoStack.canRedoChanged.connect(self.canRedoChanged)
        self.__undoStack.canUndoChanged.connect(self.canUndoChanged)
        self.__undoStack.cleanChanged.connect(self.__cleanChanged)

        self.imageChanged.connect(self.__updatePreviewPixmap)
        QApplication.clipboard().dataChanged.connect(self.__checkClipboard)

        self.__checkClipboard()
Ejemplo n.º 28
0
 def __render_icon_by_path_convert(path: str) -> QtGui.QIcon:
     '''
     返回灰度icon
     '''
     icon = QtGui.QIcon()
     image = QtGui.QPixmap(path).toImage()
     for x in range(image.width()):
         for y in range(image.height()):
             color = image.pixel(x, y)
             gray = qGray(color)
             image.setPixel(x, y, qRgba(gray, gray, gray, qAlpha(color)))
     icon.addPixmap(QtGui.QPixmap.fromImage(image), QtGui.QIcon.Normal,
                    QtGui.QIcon.On)
     return icon
Ejemplo n.º 29
0
    def setTransparentGround(self, enabled):
        if self.m_volumeItem is not None:
            newAlpha = self.terrainTransparency if enabled else 255

            for i in range(self.aboveWaterGroundColorsMin,
                           self.underWaterGroundColorsMax):
                oldColor1 = self.m_colorTable1[i]
                oldColor2 = self.m_colorTable2[i]
                self.m_colorTable1[i] = qRgba(qRed(oldColor1),
                                              qGreen(oldColor1),
                                              qBlue(oldColor1), newAlpha)
                self.m_colorTable2[i] = qRgba(qRed(oldColor2),
                                              qGreen(oldColor2),
                                              qBlue(oldColor2), newAlpha)

            if self.m_usingPrimaryTable:
                self.m_volumeItem.setColorTable(self.m_colorTable1)
            else:
                self.m_volumeItem.setColorTable(self.m_colorTable2)

            self.adjustSliceX(self.m_sliceSliderX.value())
            self.adjustSliceY(self.m_sliceSliderY.value())
            self.adjustSliceZ(self.m_sliceSliderZ.value())
Ejemplo n.º 30
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent widget (QWidget)
     """
     super(IconEditorGrid, self).__init__(parent)
     
     self.setAttribute(Qt.WA_StaticContents)
     self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
     
     self.__curColor = Qt.black
     self.__zoom = 12
     self.__curTool = self.Pencil
     self.__startPos = QPoint()
     self.__endPos = QPoint()
     self.__dirty = False
     self.__selecting = False
     self.__selRect = QRect()
     self.__isPasting = False
     self.__clipboardSize = QSize()
     self.__pasteRect = QRect()
     
     self.__undoStack = QUndoStack(self)
     self.__currentUndoCmd = None
     
     self.__image = QImage(32, 32, QImage.Format_ARGB32)
     self.__image.fill(qRgba(0, 0, 0, 0))
     self.__markImage = QImage(self.__image)
     self.__markImage.fill(self.NoMarkColor.rgba())
     
     self.__compositingMode = QPainter.CompositionMode_SourceOver
     self.__lastPos = (-1, -1)
     
     self.__gridEnabled = True
     self.__selectionAvailable = False
     
     self.__initCursors()
     self.__initUndoTexts()
     
     self.setMouseTracking(True)
     
     self.__undoStack.canRedoChanged.connect(self.canRedoChanged)
     self.__undoStack.canUndoChanged.connect(self.canUndoChanged)
     self.__undoStack.cleanChanged.connect(self.__cleanChanged)
     
     self.imageChanged.connect(self.__updatePreviewPixmap)
     QApplication.clipboard().dataChanged.connect(self.__checkClipboard)
     
     self.__checkClipboard()
Ejemplo n.º 31
0
    def __getSelectionImage(self, cut):
        """
        Private method to get an image from the selection.
        
        @param cut flag indicating to cut the selection (boolean)
        @return image of the selection (QImage)
        """
        if cut:
            cmd = IconEditCommand(self, self.tr("Cut Selection"), self.__image)

        img = QImage(self.__selRect.size(), QImage.Format_ARGB32)
        img.fill(qRgba(0, 0, 0, 0))
        for i in range(0, self.__selRect.width()):
            for j in range(0, self.__selRect.height()):
                if self.__image.rect().contains(self.__selRect.x() + i,
                                                self.__selRect.y() + j):
                    if self.__isMarked(self.__selRect.x() + i,
                                       self.__selRect.y() + j):
                        img.setPixel(
                            i, j,
                            self.__image.pixel(self.__selRect.x() + i,
                                               self.__selRect.y() + j))
                        if cut:
                            self.__image.setPixel(self.__selRect.x() + i,
                                                  self.__selRect.y() + j,
                                                  qRgba(0, 0, 0, 0))

        if cut:
            self.__undoStack.push(cmd)
            cmd.setAfterImage(self.__image)

        self.__unMark()

        if cut:
            self.update(self.__selRect)

        return img
Ejemplo n.º 32
0
def adjustSaturation(image: QImage, value) -> QImage:
    width, height = image.width(), image.height()
    newImage = QImage(width, height, QImage.Format_RGBA8888)
    for h in range(height):
        for w in range(width):
            pixel = QColor(image.pixel(h, w)).toHsl()
            H = pixel.hue()
            S = pixel.saturation() + value
            L = pixel.lightness()
            S = bound(0, 255, S)
            pixel.setHsl(H, S, L)
            newImage.setPixel(
                h, w,
                qRgba(pixel.red(), pixel.green(), pixel.blue(), pixel.alpha()))
    return newImage
Ejemplo n.º 33
0
 def __getSelectionImage(self, cut):
     """
     Private method to get an image from the selection.
     
     @param cut flag indicating to cut the selection (boolean)
     @return image of the selection (QImage)
     """
     if cut:
         cmd = IconEditCommand(self, self.tr("Cut Selection"),
                               self.__image)
     
     img = QImage(self.__selRect.size(), QImage.Format_ARGB32)
     img.fill(qRgba(0, 0, 0, 0))
     for i in range(0, self.__selRect.width()):
         for j in range(0, self.__selRect.height()):
             if self.__image.rect().contains(self.__selRect.x() + i,
                                             self.__selRect.y() + j):
                 if self.__isMarked(
                         self.__selRect.x() + i, self.__selRect.y() + j):
                     img.setPixel(i, j, self.__image.pixel(
                         self.__selRect.x() + i, self.__selRect.y() + j))
                     if cut:
                         self.__image.setPixel(self.__selRect.x() + i,
                                               self.__selRect.y() + j,
                                               qRgba(0, 0, 0, 0))
     
     if cut:
         self.__undoStack.push(cmd)
         cmd.setAfterImage(self.__image)
     
     self.__unMark()
     
     if cut:
         self.update(self.__selRect)
     
     return img
Ejemplo n.º 34
0
    def set_colors(data: bin, fg: QColor, bg: QColor, trans: QColor) -> bin:  # pylint: disable=too-many-locals
        """
        Burns foreground and background colors into a raster image, and returns
        the results as a PNG binary
        """
        image = QImage()
        image.loadFromData(data)

        image = image.convertToFormat(QImage.Format_ARGB32)
        ucharptr = image.bits()
        ucharptr.setsize(image.byteCount() * image.height())

        fg_rgba = qRgba(fg.red(), fg.green(), fg.blue(),
                        fg.alpha()) if fg and fg.isValid() else None
        bg_rgba = qRgba(bg.red(), bg.green(), bg.blue(),
                        bg.alpha()) if bg and bg.isValid() else None

        # TODO: what's this even for?
        _ = qRgba(trans.red(), trans.green(), trans.blue(),
                  trans.alpha()) if trans else None

        for y in range(image.height()):
            start = y * image.width() * 4
            for x in range(image.width()):
                x_start = x * 4 + start
                rgba = struct.unpack('I', ucharptr[x_start:x_start + 4])[0]

                if fg_rgba is not None and rgba == 0xff000000:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', fg_rgba)
                elif bg_rgba is not None and rgba == 0xffffffff:
                    ucharptr[x_start:x_start + 4] = struct.pack('I', bg_rgba)

        # convert to PNG
        png_data = QBuffer()
        image.save(png_data, "png")
        return png_data.data()
Ejemplo n.º 35
0
 def generate_grand_note(cls, note_file_prefix, span, tiny=False):
     l = NOTE_PICS["{}1.png".format(note_file_prefix)]
     m = NOTE_PICS["{}2.png".format(note_file_prefix)]
     r = NOTE_PICS["{}3.png".format(note_file_prefix)]
     w = span * LANE_DISTANCE_GRAND
     if tiny:
         w = w * 0.75
     res = QImage(l.width() + r.width() + w, l.height(),
                  QImage.Format_ARGB32)
     res.fill(qRgba(0, 0, 0, 0))
     painter = QPainter(res)
     painter.drawImage(QPoint(0, 0), l)
     painter.drawImage(QRectF(l.width(), 0, w, m.height()), m,
                       QRectF(0, 0, m.width(), m.height()))
     painter.drawImage(QPoint(l.width() + w, 0), r)
     return res
Ejemplo n.º 36
0
    def setImage(self, image):
        """ Set the scene's current image (input image must be a QImage)
        """

        if image is None:

            qimg = QImage(self.THUMB_SIZE, self.THUMB_SIZE,
                          QImage.Format_ARGB32)
            qimg.fill(qRgba(40, 40, 40, 255))
            self.pixmap = QPixmap.fromImage(qimg)
            self.imgwidth = self.THUMB_SIZE
            self.imgheight = self.THUMB_SIZE

        elif type(image) is QImage:
            imageARGB32 = image.convertToFormat(QImage.Format_ARGB32)
            self.pixmap = QPixmap.fromImage(imageARGB32)
            self.imgwidth = image.width()
            self.imgheight = image.height()
        else:
            raise RuntimeError("Argument must be a QImage.")

        if self.hasImage():
            self.pixmapitem.setPixmap(self.pixmap)
        else:
            self.pixmapitem = self.scene.addPixmap(self.pixmap)

        # Set scene size to image size (!)
        self.setSceneRect(QRectF(self.pixmap.rect()))

        if self.imgwidth > self.imgheight:

            aspectratio = self.imgheight / self.imgwidth
            h = (int)(aspectratio * self.width())
            self.setFixedHeight(h)

        # calculate zoom factor
        pixels_of_border = 10
        zf1 = (self.geometry().width() - pixels_of_border) / self.imgwidth
        zf2 = (self.geometry().height() - pixels_of_border) / self.imgheight

        zf = min(zf1, zf2)
        if zf > 1.0:
            zf = 1.0

        self.zoom_factor = zf

        self.updateViewer()
Ejemplo n.º 37
0
def adjustContrast(image: QImage, value) -> QImage:
    width, height = image.width(), image.height()
    newImage = QImage(width, height, QImage.Format_RGBA8888)
    if value >= 0:
        value = 1 / (1 - value / 100.0) - 1
    else:
        value /= 100.0
    for h in range(height):
        for w in range(width):
            pixel = QColor(image.pixel(h, w))
            color = [
                bound(0, 255, (c - 127) * value + c)
                for c in [pixel.red(
                ), pixel.green(), pixel.blue()]
            ]
            newImage.setPixel(h, w, qRgba(*color, pixel.alpha()))
    return newImage
Ejemplo n.º 38
0
def adjustWarm(image: QImage, value) -> QImage:
    width, height = image.width(), image.height()
    newImage = QImage(width, height, QImage.Format_RGBA8888)
    for h in range(height):
        for w in range(width):
            pixel = QColor(image.pixel(h, w))
            red, green, blue = pixel.red(), pixel.green(), pixel.blue()
            if value >= 0:
                red += value
                red = bound(0, 255, red)
                green += value
                green = bound(0, 255, green)
            else:
                blue += abs(value)
                blue = bound(0, 255, blue)
            newImage.setPixel(h, w, qRgba(red, green, blue, pixel.alpha()))
    return newImage
Ejemplo n.º 39
0
def test_rgb():
    # from https://qt-project.org/doc/qt-4.8/qcolor.html
    # typedef QRgb
    # An ARGB quadruplet on the format #AARRGGBB, equivalent to an unsigned int.

    assert_equal(qRgb(0,0,0), qRgba(0,0,0,255))
    
    def checkrgb(r,g,b):
        val = ImageQt.rgb(r,g,b)
        val = val % 2**24 # drop the alpha
        assert_equal(val >> 16, r)
        assert_equal(((val >> 8 ) % 2**8), g)
        assert_equal(val % 2**8, b)
        
    checkrgb(0,0,0)
    checkrgb(255,0,0)
    checkrgb(0,255,0)
    checkrgb(0,0,255)
Ejemplo n.º 40
0
 def __setImagePixel(self, pos, opaque):
     """
     Private slot to set or erase a pixel.
     
     @param pos position of the pixel in the widget (QPoint)
     @param opaque flag indicating a set operation (boolean)
     """
     i, j = self.__imageCoordinates(pos)
     
     if self.__image.rect().contains(i, j) and (i, j) != self.__lastPos:
         if opaque:
             painter = QPainter(self.__image)
             painter.setPen(self.penColor())
             painter.setCompositionMode(self.__compositingMode)
             painter.drawPoint(i, j)
         else:
             self.__image.setPixel(i, j, qRgba(0, 0, 0, 0))
         self.__lastPos = (i, j)
     
         self.update(self.__pixelRect(i, j))
Ejemplo n.º 41
0
def draw_icon(icon, rect, painter, icon_mode, shadow=False):
    cache = icon.pixmap(rect.size())
    dip_offset = QPoint(1, -2)

    cache = QPixmap()
    pixname = "icon {0} {1} {2}".format(
        icon.cacheKey(), icon_mode, rect.height()
    )
    if QPixmapCache.find(pixname) is None:
        pix = icon.pixmap(rect.size())
        device_pixel_ratio = pix.devicePixelRatio()
        radius = 3 * device_pixel_ratio
        offset = dip_offset * device_pixel_ratio
        cache = QPixmap(pix.size() + QSize(radius * 2, radius * 2))
        cache.fill(Qt.transparent)

        cache_painter = QPainter(cache)

        if icon_mode == QIcon.Disabled:
            im = pix.toImage().convertToFormat(QImage.Format_ARGB32)
            for y in range(0, im.height()):
                scanline = im.scanLine(y)
                for x in range(0, im.width()):
                    pixel = scanline
                    intensity = qGray(pixel)
                    scanline = qRgba(
                        intensity, intensity, intensity, qAlpha(pixel))
                    scanline += 1
            pix = QPixmap.fromImage(im)

        # Draw shadow
        tmp = QImage(pix.size() + QSize(radius * 2, radius * 2),
                     QImage.Format_ARGB32_Premultiplied)
        tmp.fill(Qt.transparent)

        tmp_painter = QPainter(tmp)
        tmp_painter.setCompositionMode(QPainter.CompositionMode_Source)
        tmp_painter.drawPixmap(
            QRect(radius, radius, pix.width(), pix.height()), pix)
        tmp_painter.end()

        # Blur the alpha channel
        blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied)
        blur_painter = QPainter(blurred)
        blur_painter.end()

        # tmp = blurred

        tmp_painter.begin(tmp)
        tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150))
        tmp_painter.end()

        tmp_painter.begin(tmp)
        tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150))
        tmp_painter.end()

        # Draw the blurred drop shadow
        cache_painter.drawImage(
            QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp)
        # Draw the actual pixmap
        cache_painter.drawPixmap(
            QRect(QPoint(radius, radius) + offset,
                  QSize(pix.width(), pix.height())), pix)
        cache_painter.end()
        cache.setDevicePixelRatio(device_pixel_ratio)
        QPixmapCache.insert(pixname, cache)

    target_rect = cache.rect()
    target_rect.setSize(target_rect.size() / cache.devicePixelRatio())
    target_rect.moveCenter(rect.center() - dip_offset)
    painter.drawPixmap(target_rect, cache)
def rgb(r, g, b, a=255):
    # 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)
Ejemplo n.º 43
0
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)