2012-02-16 89 views
0

我写了一些代码,应该使一个新的形象。我的背景图像有黑色区域,当for循环出现黑色像素时,它应该在新图像中绘制蓝色区域,否则应该绘制原始像素。以为我可以这样做,但程序不断运行。Qt绘制一个蓝色的像素,如果原始像素是在一个新的图像黑色

QApplication a(argc, argv); 
int c, m, y, k, al; 
QColor color; 
QColor drawColor; 
QImage background; 
QImage world(1500, 768, QImage::Format_RGB32); 
QSize sizeImage; 
int height, width; 
background.load("Background.jpg"); 
world.fill(1); 
QPainter painter(&background); 
sizeImage = background.size(); 
width = sizeImage.width(); 
height = sizeImage.height(); 

for(int i = 0; i < height; i++) 
{ 
    for(int z = 0; z < width; z++) 
    { 
     color = QColor::fromRgb (background.pixel(i,z)); 
     color.getCmyk(&c,&m,&y,&k,&al); 

     if(c == 0 && m == 0 && y == 0 && k == 0) //then we have black as color and then we draw the color blue 
     { 
      drawColor.setBlue(255); 
      painter.setPen(drawColor); 
      painter.drawPoint(i,z); 
     } 
    } 

} 


//adding new image to the graphicsScene 
QGraphicsPixmapItem item(QPixmap::fromImage(background)); 
QGraphicsScene* scene = new QGraphicsScene; 
scene->addItem(&item); 

QGraphicsView view(scene); 
view.show(); 

是我的循环错误还是我的画家?它是QImage :: pixel:坐标(292,981)超出范围,但对于很多像素来说,它的速度还不够快。

+0

你是什么意思的“程序继续运行”?它永远不会出现for循环?你没有得到你期望的结果? – Bart 2012-02-16 13:06:16

+0

仅仅是因为循环速度非常慢?在我看来,通过读取和写入像这样的单个像素来转换大图像会稍微滞后! – Robinson 2012-02-16 13:14:41

+0

那么什么是更好的方法?我想也许只是重新绘制蓝色像素,但我不知道如何在图像上循环。 – user1007522 2012-02-16 13:27:40

回答

2

正如评论中指出的那样,逐个绘制像素可能会非常慢。即使逐像素访问也可以是quite slow。例如。以下是可能更快,但仍然不太好:

const QRgb black = 0; 
    const QRgb blue = 255; 
    for(int y = 0; y < height; y++) { 
    for(int x = 0; x < width; x++) { 
     if (background.pixel(x,y) == black) { 
     background.SetPixel(blue); 
     } 
    } 
    } 

的更快的解决方案通过scanline()涉及直接bitoperations。您可能首先要致电convertToFormat(),因此您无需处理不同的可能扫描线格式。

作为一个创造性的黑客,请致电createMaskFromColor使所有黑色像素透明,然后绘制在蓝色背景上。

+0

感谢这非常快速,但代码不会将任何内容更改为蓝色。 – user1007522 2012-02-16 13:53:31

+0

那么,我没有看到实际的绘画部分。这只是改变'QImage背景'。你仍然需要一个'painter.drawImage()'调用。 (哦,它对黑色非常挑剔,深灰色不是黑色)。 – MSalters 2012-02-16 13:59:47

+0

好的,所以在整个while循环之后,我只需要再次绘制图像,或者您是否在if测试中指向? – user1007522 2012-02-16 14:02:18

相关问题