2012-01-26 87 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