2011-10-21 40 views
1

我試圖加載這樣的圖像的字節數:獲取圖像的字節數

NSURL *img = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"img" ofType:@"png"] isDirectory:NO]; 
NSString * test = [NSString stringWithContentsOfFile:[img absoluteString] encoding:NSASCIIStringEncoding error:&err]; 

但我總是得到以下錯誤:

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn\u2019t be completed. 
(Cocoa error 260.)" UserInfo=0xc02abf0 
{NSFilePath=file://localhost/Users/admin/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/C55551DB-152A-43D6-A1E0-9845105709D6/myApp.app/img.png, 
NSUnderlyingError=0xc02ccc0 "The operation couldn\u2019t be completed. Folder or file does not exist"} 

但該文件確實存在,而且如果我複製/將NSFilePath粘貼到瀏覽器中找到圖像。什麼可能是錯的?

回答

2

爲什麼不

NSString *path = [[NSBundle mainBundle] pathforResource:@"img" ofType:"png"]; 

NSData *data = [NSData dataWithContentsOfFile:path]; 

你不能只是存儲在一個NSString隨機字節 - 它會嘗試將它們轉換爲字符串,並可能會失敗。您需要爲二進制數據使用NSData對象。

你也不需要使用NSURL; NSBundle會給你一個字符串的路徑。

+0

其實,這取決於你想要什麼,@beryllium有一個很好的答案的!用我的答案,你不僅可以獲取圖像的字節,還可以獲得.png文件所有額外的東西 - beryllium的答案_only_爲您提供圖像數據。 – deanWombourne

1

在使用文件URL時,請在第二行使用[img path]而不是[img absoluteString]

或在第一行使用[NSURL URLWithPath]

1

存儲字節的NSData:

NSData *bytes = UIImagePNGRepresentation([UIImage imageNamed:@"myImage.png"]); 
0
NSData* imageData = UIImagePNGRepresentation("imagename.."); //the image is converted to bytes 
+0

這甚至不會編譯:(''UIImagePNGRepresentation'需要一個'UIImage *',而不是'char *' - 請看@ beryllium的答案,你正在嘗試做什麼。 – deanWombourne

相關問題