【问题标题】:Get image bytes获取图像字节
【发布时间】:2011-10-21 09:45:32
【问题描述】:

我正在尝试像这样加载图像的字节:

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 复制/粘贴到浏览器中,它会找到图像。有什么问题?

【问题讨论】:

    标签: iphone nsstring nsurl nsbundle


    【解决方案1】:

    为什么不

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

    您不能只在 NSString 中存储随机字节 - 它会尝试将它们转换为字符串并且可能会失败。二进制数据需要使用 NSData 对象。

    您也根本不需要使用 NSURL; NSBundle 会给你一个字符串形式的路径。

    【讨论】:

    • 实际上,根据您的需要,@beryllium 也有一个很好的答案!根据我的回答,您不仅会获得图像的字节数,还会获得 .png 文件具有的所有额外内容 - 铍的回答 only 会为您提供图像数据。跨度>
    【解决方案2】:

    当您使用文件 URL 时,请在第二行使用 [img path] 而不是 [img absoluteString]

    或者在第一行使用[NSURL URLWithPath]

    【讨论】:

      【解决方案3】:

      在 NSData 中存储字节:

      NSData *bytes = UIImagePNGRepresentation([UIImage imageNamed:@"myImage.png"]);
      

      【讨论】:

        【解决方案4】:
         NSData* imageData = UIImagePNGRepresentation("imagename.."); //the image is converted to bytes
        

        【讨论】:

        • 这甚至不会编译 :( UIImagePNGRepresentation 需要 UIImage *,而不是 char* - 请查看 @beryllium 的答案以了解您想要做什么。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-10
        • 2016-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多