【问题标题】:I need to get array of bytes from image我需要从图像中获取字节数组
【发布时间】:2014-03-06 11:33:30
【问题描述】:

我正在尝试获取包含图像字节的字节数组,如下所示:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
unsigned char *bytesArray = data.bytes;
NSUInteger lengthOfBytesArray = data.length;

接下来,我尝试将这些值复制到一个数组中。

    if (data.length>0)
    {
        NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:data.length];
        for (int i = 0; i<data.length; i++) {
            unsigned char byteFromArray = bytesArray[i];
            [array addObject:[NSValue valueWithBytes:&byteFromArray objCType:@encode(unsigned char)]];

        }
    }

最后在调试中我收到了空对象数组。它们有内存地址但没有值(NSConcreateValue 类型)。同样在调试区域,我检查了byteFromArray,它是一个`(unsigned char)'P'。我是否选择了错误的方式从图像中获取字节数组,还是我的代码错误?

【问题讨论】:

    标签: objective-c encoding nsmutablearray bytearray


    【解决方案1】:

    尝试替换这个

        for (int i = 0; i<data.length; i++) {
            unsigned char byteFromArray = bytesArray[i];
            [array addObject:[NSValue valueWithBytes:&byteFromArray objCType:@encode(unsigned char)]];
        }
    

    有了这个

        for (int i = 0; i<data.length; i++) 
            [array addObject:[NSNumber numberWithUnsignedChar:bytesArray[i]]];
    

    另外,我建议添加一个 NSLog 来显示 data.length 只是为了查看有多少元素被添加到数组中。

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多