2012-01-26 88 views
0

這是我第一次關於圖像處理任務。我假定輸出圖像上的每個像素的索引被表示爲如下矩陣:如何在iPhone上的圖像上按像素添加顏色?

00 01 02 03 04 05 

10 11 12 13 14 15 

20 21 22 23 24 25 

在輸出圖像的每個索引我有不同的顏色來繪製上。例如,在索引00處,我有redcolor可用於放置在其他索引等。我的問題是如何將這些顏色繪製到索引中以創建輸出圖像?

更新

這就是我現在所擁有的:

inputImgAvg //Image for processing 
CGContextRef context = UIGraphicsGetCurrentContext(); 

float yy = groutW/2;   // skip over grout on edge 
    float stride =(int) (tileW + groutW +0.5); 
     for(int y=0; y<tilesY; y++) {    //Number tile in Y direction 
      float xx = groutW/2 ;   // skip over grout on edge 
      for(int x=0; x<tilesX; x++) { 
       tileRGB = [inputImgAvg colorAtPixel:CGPointMake(x,y)]; 

       //Right here I'm checking tileRGB with list of available color 
       //Find out the closest color 
       //Now i'm just checking with greenColor 

       // best matching tile is found in idx position in vector; 
       // scale and copy it into proper location in the output 
       CGContextSetFillColor(context, CGColorGetComponents([[UIColor greenColor] CGColor])); 

但我得到這個錯誤。你能指出我做錯了什麼嗎?

<Error>: CGContextSetFillColor: invalid context 0x0 
<Error>: CGContextFillRects: invalid context 0x0 
+0

爲什麼有-1? – user1139699 2012-01-26 23:44:00

+0

如果你真的嘗試你的任務,然後詢問你遇到的具體問題,你會從堆棧溢出中得到最好的迴應。 – theTRON 2012-01-26 23:52:03

+0

我認爲這個問題可能是你正在尋找的: http://stackoverflow.com/questions/448125/how-to-get-pixel-data-from-a-uiimage-cocoa-touch-or -cgimage-core-graphics – 2012-01-26 23:52:32

回答

2

這線程回答了這個問題:

http://www.iphonedevsdk.com/forum/iphone-sdk-development/34247-cgimage-pixel-array.html

創建一個CGContext上使用CGBitmapContextCreate,它可以讓你提供數據的圖像。然後,您可以使用指針將像素寫入數據並自行設置字節。

一旦你完成了,使用UIGraphicsGetImageFromCurrentContext()或等價物來獲取上下文數據到UIImage對象。

如果這一切看起來有點低級別,另一個選擇是創建一個CGContext並繪製1x1矩形。它不會很快,但不會像你想象的那麼慢,因爲CG函數都是純C,任何冗餘都會被編譯器優化:

//create drawing context 
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0f); 
CGContextRef context = UIGraphicsGetCurrentContext(); 

//draw pixels 
for (int x = 0; x < width; x++) 
{ 
    for (int y = 0; y < height; y++) 
    { 
     CGContextSetFillColor(... your color here ...); 
     CGContextFillRect(context, CGRectMake(x, y, 1.0f, 1.0f)); 
    } 
} 

//capture resultant image 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
+0

謝謝你的回答。這對我幫助很大。但是我不明白你的意思是「你可以通過使用指針將像素寫入數據」。我使用CGDataProviderCopyData來獲取源圖像的​​數據。我將數據轉換爲UInt8。現在我怎麼能通過使用指針來傳遞需要繪製到數據中的顏色? – user1139699 2012-02-05 07:59:47

+0

使用CGDataProviderCopyData可能不起作用,因爲您需要處理圖像的實際數據,而不是其副本。每個像素由4個UInt8組成,紅,綠,藍,阿爾法。這就是顏色的製作方式。圖像數據只是反覆4個字節,所以請嘗試設置字節並查看結果。由於有一些額外的間距字節,所以在每一行顏色的末尾可能必須小心。 – 2012-02-05 11:02:57

+0

謝謝你的忠告 – user1139699 2012-02-06 03:28:54