如何在Objective-c中将UIImage转换为字节数组

时间:2016-08-30 08:43:23

标签: ios objective-c uiimage nsarray bytearray

我正在将.nextAll()转换为UIImage,就像这样

byte

当我在日志中打印此NSUInteger len = [imageData length]; Byte *byteData= (Byte*)malloc(len); memcpy(byteData, [imageData bytes], len); 时,我会看到这样的值。

byteData

但是如何从中创建一个字节数组呢? 请帮我。 感谢

更新

这就是我们的Web应用程序将数据传递到同一服务的方式。

(lldb) po byteData
"\377\330\377\340

所以我想在我的iOS应用程序中做同样的事情。

3 个答案:

答案 0 :(得分:0)

您必须将UIImage转换为NSData,如下所示:

UIImage * imgObj = [UIImage imageNamed:@" image.jpg"];

NSData * imgData = UIImageJPEGRepresentation(imgObj,0.9);

答案 1 :(得分:0)

可能低于代码可能有所帮助:

@try {
    NSData *data = UIImagePNGRepresentation(img);
    NSUInteger len = data.length;
    uint8_t bytes = (uint8_t )[data bytes];
    NSMutableString *result = [NSMutableString stringWithCapacity:len];
    for (NSUInteger i = 0; i < len; i++) {
        if (i) {
            [result appendString:@","];
        }
        [result appendFormat:@"%d",bytes];
    }
    return result;
} @catch (NSException * e) {
    NSLog(@"Exception: %@", e);
}
@finally {
    NSLog(@"finally");
}

答案 2 :(得分:0)

这是最简单的方法......

UIImage *img =  [UIImage imageNamed:@"yourimage.png"];

NSData *imageData = UIImagePNGRepresentation(img);

UIImage *img =  [UIImage imageNamed:@"yourimage.jpg"];

CGFloat quality = 0.80;

NSData *imageData = UIImageJPEGRepresentation(img,quality);