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_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, image in enumerate(self.layers): if progress.wasCanceled(): break progress.setValue(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, image in enumerate(self.layers): if progress.wasCanceled(): break progress.setValue(z) packed_value = height_packed[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 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 save_image_to(self, path): TOP_MARGIN = 50 LEFT_MARGIN = 50 # Determine the size of the entire graph graph_size = self._graph_size() image_size = QSize(graph_size.width() + LEFT_MARGIN * 2, graph_size.height() + TOP_MARGIN * 2 ) image = QImage(image_size, QImage.Format_ARGB32) image.fill(Qt.white) # white background painter = QPainter(image) painter.translate(TOP_MARGIN, LEFT_MARGIN) painter.setRenderHint(QPainter.TextAntialiasing) self._paint(painter, QPoint(-TOP_MARGIN, -LEFT_MARGIN), QPoint(image_size.width(), image_size.height()) ) painter.end() image.save(path)
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 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 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);
def saveAsBitmap(self, fn): """ Save bar image as a jpg file. Overwrites a file already existing in filesystem. https://stackoverflow.com/questions/7451183/how-to-create-image-file\ -from-qgraphicsscene-qgraphicsview#11642517 Args: fn: Filename Returns: True on success """ size = self.size pixelsx = max(1200, size[0]) pixelsy = int(pixelsx*size[1]/size[0]) imagesize = (pixelsx, pixelsy) image = QImage(pixelsx, pixelsy, QImage.Format_ARGB32_Premultiplied) painter = QPainter(image) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.setPen(Qt.white) painter.drawRect(QRect(0, 0, *imagesize)) targetrect = QRectF(0, 0, *imagesize) sourcerect = QRectF(0, 0, *size) self.render(painter, targetrect, sourcerect) painter.end() return image.save(fn)
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 getContacts(self): contacts = self.store.Contact.fetchAll(); if len(contacts) == 0: #print "RESYNCING"; #self.resync(); return contacts; #O(n2) matching, need to change that cm = self.manager phoneContacts = cm.getContacts(); tmp = [] self.contacts = {}; if not os.path.exists("/home/user/.cache/wazapp/contacts"): os.makedirs("/home/user/.cache/wazapp/contacts") for wc in contacts: for c in phoneContacts: if wc.number == c['number']: #@@TODO cache to enhance startup jname = wc.jid.replace("@s.whatsapp.net","") if not os.path.isfile("/home/user/.cache/wazapp/contacts/" + jname + ".png"): user_img = QImage(QUrl(c['picture']).toString().replace("file://","")) if os.path.isfile("/home/user/.cache/wazapp/contacts/" + jname + ".jpg"): user_img = QImage("/home/user/.cache/wazapp/contacts/" + jname + ".jpg") mask_img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/usermask.png") preimg = QPixmap.fromImage(QImage(user_img.scaled(96, 96, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))); PixmapToBeMasked = QImage(96, 96, QImage.Format_ARGB32_Premultiplied); Mask = QPixmap.fromImage(mask_img); Painter = QPainter(PixmapToBeMasked); Painter.drawPixmap(0, 0, 96, 96, preimg); Painter.setCompositionMode(QPainter.CompositionMode_DestinationIn); Painter.drawPixmap(0, 0, 96, 96, Mask); Painter.end() PixmapToBeMasked.save("/home/user/.cache/wazapp/contacts/" + jname + ".png", "PNG") if os.path.isfile("/home/user/.cache/wazapp/contacts/" + jname + ".jpg"): os.remove("/home/user/.cache/wazapp/contacts/" + jname + ".jpg") c['picture'] = "/home/user/.cache/wazapp/contacts/" + jname + ".png"; wc.setRealTimeData(c['name'],c['picture']); if wc.status is not None: wc.status = wc.status.decode('utf-8'); #tmp.append(wc.toModel()); tmp.append(wc.getModelData()); self.contacts[wc.number] = wc; break; self.store.cacheContacts(self.contacts); return sorted(tmp, key=lambda k: k['name'].upper()) ;
def updateContact(self,jid): jname = jid.replace("@s.whatsapp.net","").replace("@g.us","") user_img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/user.png") user_img.save("/home/user/.cache/wazapp/contacts/" + jname + ".png", "PNG") user_img = QImage("/home/user/.cache/wazapp/contacts/" + jname + ".jpg") mask_img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/usermask.png") preimg = QPixmap.fromImage(QImage(user_img.scaled(96, 96, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))); PixmapToBeMasked = QImage(96, 96, QImage.Format_ARGB32_Premultiplied); Mask = QPixmap.fromImage(mask_img); Painter = QPainter(PixmapToBeMasked); Painter.drawPixmap(0, 0, 96, 96, preimg); Painter.setCompositionMode(QPainter.CompositionMode_DestinationIn); Painter.drawPixmap(0, 0, 96, 96, Mask); Painter.end() PixmapToBeMasked.save("/home/user/.cache/wazapp/contacts/" + jname + ".png", "PNG") os.remove("/home/user/.cache/wazapp/contacts/" + jname + ".jpg") self.contactUpdated.emit(jid);
def save(self, bin_name): # Создаём изображение для контейнера image = QImage(self.size.width, self.size.height, QImage.Format_ARGB32) # Рисуем контейнер в изображение painter = QPainter(image) self.draw(painter, Point(), draw_mode=self.DRAW_MODE_RELEASE) bin_file_name = bin_name + '.png' # Если изображение для контейнера существует, удаляем if os.path.exists(bin_file_name): os.remove(bin_file_name) # Сохраняем изображение контейнера image.save(bin_file_name) painter.end() Bin.exporter.export(bin_name, self.size, self.images)
def loadConversations(self): conversations = self.store.ConversationManager.findAll(); self._d("init load convs") for c in conversations: self._d("loading messages") jid = c.getJid(); c.loadMessages(); self.conversations[jid] = c print "loaded messages" if "@g.us" in jid: jname = jid.replace("@g.us","") if not os.path.isfile("/home/user/.cache/wazapp/contacts/" + jname + ".png"): img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/group.png") img.save("/home/user/.cache/wazapp/contacts/" + jname + ".png") self.sendConversationReady(jid); self.sendMessagesReady(jid,c.messages);
def checkPicture(self,jname,imagepath): if not os.path.isfile("/home/user/.cache/wazapp/contacts/" + jname + ".png"): user_img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/user.png") if imagepath is not "": user_img = QImage(QUrl(imagepath).toString().replace("file://","")) if os.path.isfile("/home/user/.cache/wazapp/contacts/" + jname + ".jpg"): user_img = QImage("/home/user/.cache/wazapp/contacts/" + jname + ".jpg") mask_img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/usermask.png") preimg = QPixmap.fromImage(QImage(user_img.scaled(96, 96, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))); PixmapToBeMasked = QImage(96, 96, QImage.Format_ARGB32_Premultiplied); Mask = QPixmap.fromImage(mask_img); Painter = QPainter(PixmapToBeMasked); Painter.drawPixmap(0, 0, 96, 96, preimg); Painter.setCompositionMode(QPainter.CompositionMode_DestinationIn); Painter.drawPixmap(0, 0, 96, 96, Mask); Painter.end() PixmapToBeMasked.save("/home/user/.cache/wazapp/contacts/" + jname + ".png", "PNG") if os.path.isfile("/home/user/.cache/wazapp/contacts/" + jname + ".jpg"): os.remove("/home/user/.cache/wazapp/contacts/" + jname + ".jpg")
def save_invoice(self, ok): self.enable_ui() if ok: frame = self.webpage.mainFrame() image = QImage(frame.contentsSize(), QImage.Format_ARGB32_Premultiplied) image.fill(Qt.transparent); painter = QPainter(image) painter.setRenderHint(QPainter.Antialiasing, True); painter.setRenderHint(QPainter.TextAntialiasing, True); painter.setRenderHint(QPainter.SmoothPixmapTransform, True); frame.documentElement().render(painter); painter.end(); image.save(self.invoice_filename) self.load_invoice() else: title = "An error occured" message = "Could not load invoice." \ + "\nPlease check your internet connection." QMessageBox.critical(self, title, message)
class ImagenQImage(BaseImagen): def __init__(self): super(ImagenQImage, self).__init__() self.mode = "No implementado" @property def size(self): return (self.img.width(), self.img.height()) def fromfile(self, filename): self.img = QImage(filename) def from_instance(self, qimage): self.img = qimage def empty(self, size, mode=QImage.Format_RGB888): self.img = QImage(size[0], size[1], mode) self.img.fill(qRgb(0, 0, 0)) #Rellenamos la imagen con negro def getpixel(self, xy): color = self.img.pixel(xy[0], xy[1]) return (qRed(color), qGreen(color), qBlue(color)) def putpixel(self, xy, value): self.img.setPixel(xy[0], xy[1], qRgb(value[0], value[1], value[2])) def get_img(self): return self.img def save(self, filename): self.img.save(filename, format="BMP", quality=100) def from_opencv(self, img_opencv): dst = cv2.cvtColor(img_opencv, cv2.COLOR_BGR2RGB) qim = QImage(dst.data, dst.shape[1], dst.shape[0], dst.strides[0], QImage.Format_RGB888) self.img = qim.copy()
class ImagenQImage(BaseImagen): def __init__(self): super(ImagenQImage, self).__init__() self.mode = "No implementado" @property def size(self): return (self.img.width(), self.img.height()) def fromfile(self, filename): self.img = QImage(filename) def from_instance(self, qimage): self.img = qimage def empty(self, size, mode=QImage.Format_RGB888): self.img = QImage(size[0], size[1], mode) self.img.fill(qRgb(0,0,0))#Rellenamos la imagen con negro def getpixel(self, xy): color = self.img.pixel(xy[0], xy[1]) return (qRed(color), qGreen(color), qBlue(color)) def putpixel(self, xy, value): self.img.setPixel(xy[0], xy[1], qRgb(value[0], value[1], value[2])) def get_img(self): return self.img def save(self, filename): self.img.save(filename, format="BMP", quality=100) def from_opencv(self, img_opencv): dst = cv2.cvtColor(img_opencv, cv2.COLOR_BGR2RGB) qim = QImage(dst.data, dst.shape[1], dst.shape[0], dst.strides[0], QImage.Format_RGB888) self.img = qim.copy()
def render(self, ok): if ok: print('Loaded {0}'.format(self.url.toString())) self.webpage.setViewportSize( self.webpage.mainFrame().contentsSize()) image = QImage(self.webpage.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.webpage.mainFrame().render(painter) painter.end() if image.save(self.image_path): print('Saved image to {0}'.format(self.image_path)) else: print('Could not save to {0}'.format(self.image_path)) else: print('Could not load {0.toString()}'.format(self.url)) QApplication.instance().quit()
from PySide.QtCore import QCoreApplication from PySide.QtGui import QImage if __name__ == "__main__": app = QCoreApplication([]) img = QImage("lenna.png") w, h = img.size().width(), img.size().width() for p in ((x, y) for x in range(w) for y in range(h)): colour = img.pixel(p[0], p[1]) # AARRGGBB r = (colour >> 16) & 0xFF g = (colour >> 8) & 0xFF b = colour & 0xFF avg = round((r + g + b) / 3) # Naïve method (no colour weighting) new_colour = 0xff000000 + (avg << 16) + (avg << 8) + avg img.setPixel(p[0], p[1], new_colour) img.save("output.png")
import sys import cv2 from PySide.QtGui import QImage img_cv = cv2.imread(sys.argv[1]) print "Source image type: %s" % type(img_cv) print "Source data type %s" % img_cv.dtype print img_cv[0, 0] dst = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB) print dst[0, 0] print "Destination image type: %s" % type(dst) print "Destination data type %s" % dst.dtype h = dst.shape[0] w = dst.shape[1] qim = QImage(dst.data, w, h, dst.strides[0], QImage.Format_RGB888) qim.save("out.jpg")
import sys import cv2 from PySide.QtGui import QImage img_cv = cv2.imread(sys.argv[1]) print "Source image type: %s" % type(img_cv) print "Source data type %s" % img_cv.dtype print img_cv[0,0] dst = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB) print dst[0,0] print "Destination image type: %s" % type(dst) print "Destination data type %s" % dst.dtype h = dst.shape[0] w = dst.shape[1] qim = QImage(dst.data, w, h, dst.strides[0], QImage.Format_RGB888) qim.save("out.jpg")
def onGroupCreated(self,jid,group_id): self._d("Got group created " + group_id) jname = jid.replace("@g.us","") img = QImage("/opt/waxmppplugin/bin/wazapp/UI/common/images/group.png") img.save(WAConstants.CACHE_PATH+"/contacts/" + jname + ".png") self.groupCreated.emit(group_id);