簡體   English   中英

NSData到字節數組(或整數數組)

[英]NSData to byte array (or array of integers)

我正在使用網絡服務,該服務將圖像顯示為整數數組。 我設法使用下面的代碼將此數組轉換為NSData對象,然后轉換為UIImage 現在,我不確定如何將圖像轉換為類似的數組。

該數組如下所示:

[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,219,0,67,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,...]

這是我用來將上述數組轉換為UIImage

+ (UIImage *)imageFromBytes:(NSArray *)bytes
{
    unsigned char *buffer = (unsigned char *) malloc(bytes.count);
    int i = 0;
    for (NSDecimalNumber *num in bytes)
        buffer[i++] = num.intValue;
    NSData *data = [NSData dataWithBytes:buffer length:bytes.count];
    free(buffer);

    return [UIImage imageWithData:data];
}

因此,我需要將UIImage轉換為整數數組(字節數組)。

有人能指出我正確的方向嗎?

您可以使用以下方法獲取圖像的數據:

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

如果使用JPG,則可以使用UIImageJPEGRepresentation。

然后,提取字節數組:

NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
free(byteData)

您也可以使用NSData的方法(void)getBytes:(void *)buffer length:(NSUInteger)length

[data getBytes:&byteData length:len];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM