2012-02-16 90 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

相關問題