2011-08-29 64 views
5

我遇到了麻煩。我有一些原始的RGB數據,從0到255的值,並希望在iPhone上顯示它的圖像,但無法找到如何做到這一點。誰能幫忙?我想我可能需要使用CGImageCreate,但只是不明白。試着看着課程參考,感覺很困難。從RGB數據創建圖像?

我想要的只是從某些計算生成的10x10灰度圖像,以及是否有簡單的方法來創建png或其他很棒的東西。

+0

你可以添加一些關於你的平臺和哪種編程語言的細節嗎?你提到CGImageCreate,你可以包含一個url嗎? – eon

+1

你怎麼樣給你一些細節,你卡在哪裏?對於沒有看到其他問題的人:http://stackoverflow.com/questions/7221604/create-image-from-nsarray-data/7221751#7221751 –

回答

2

使用CGBitmapContextCreate()創建一個基於內存的位圖自己。然後致電CGBitmapContextGetData()獲取您的繪圖代碼的指針。然後CGBitmapContextCreateImage()創建一個CGImageRef

我希望這足以讓你開始。

+0

好吧,在這裏:我使用Xcode編程iOS和objective-c/coco。我陷入了困境,因爲我從來沒有使用任何石英或cgimage的東西,每個人都只是說使用CGBitmapContextCreate等,但我真的需要一個簡單的例子。 –

+0

另外,感謝您的鏈接,但我只是無法得到它的工作,並開始討論它將如何幫助我。我嘗試打印出的數據是爲unsigned char創建的,然後用它來使uiimage期待它成爲rgb數據,但我無法正確顯示它。這是使用示例項目。當我把它放入我自己的時候,它沒有縫合來正確加載我的圖像,只是拒絕NSLog。 –

+0

我發現另一個頁面看起來不錯,但我仍然沒有收到它。我對此很新。 http://stackoverflow.com/questions/1579631/converting-rgb-data-into-a-bitmap-in-objective-c-cocoa –

13

一個非常原始的例子,類似墊的建議,但這個版本使用外部像素緩衝區(pixelData):

const size_t Width = 10; 
const size_t Height = 10; 
const size_t Area = Width * Height; 
const size_t ComponentsPerPixel = 4; // rgba 

uint8_t pixelData[Area * ComponentsPerPixel]; 

// fill the pixels with a lovely opaque blue gradient: 
for (size_t i=0; i < Area; ++i) { 
    const size_t offset = i * ComponentsPerPixel; 
    pixelData[offset] = i; 
    pixelData[offset+1] = i; 
    pixelData[offset+2] = i + i; // enhance blue 
    pixelData[offset+3] = UINT8_MAX; // opaque 
} 

// create the bitmap context: 
const size_t BitsPerComponent = 8; 
const size_t BytesPerRow=((BitsPerComponent * Width)/8) * ComponentsPerPixel; 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef gtx = CGBitmapContextCreate(&pixelData[0], Width, Height, BitsPerComponent, BytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); 

// create the image: 
CGImageRef toCGImage = CGBitmapContextCreateImage(gtx); 
UIImage * uiimage = [[UIImage alloc] initWithCGImage:toCGImage]; 

NSData * png = UIImagePNGRepresentation(uiimage); 

// remember to cleanup your resources! :) 
+0

看起來像我一直在尋找的東西。唯一的問題是我現在得到馬赫O的錯誤:( –

+0

我沒有問題,我發佈的程序。可能是一個新的問題? – justin

+0

哦,我解決了它,謝謝!我不小心將CoreGraphics框架複製到我的項目文件夾。 ! –