如何在ios中将字节数组转换为图像

Pav*_*ati 2 bytearray uiimage nsdata ios

今天我的任务是将字节数组转换为图像

首先,我尝试将图像转换为字节数组:-

要将 Image 转换为 Byte 数组,我们首先要做的是将特定的图像 [ UIImage]NSData转换为。然后我们将其转换NSData为 Byte 数组。这里我将给出示例代码,只需通过...

//Converting UIImage to NSData
    UIImage *image = [UIImage imageNamed: @"photo-04.jpg"];

    NSData *imageData = UIImagePNGRepresentation(image);

    //Converting NSData to Byte array
    NSUInteger len = [imageData length];
    NSLog(@"Byte Lendata1  %lu",(unsigned long)len);

    Byte *byteData = (Byte*)malloc(len);
    memcpy(byteData, [imageData bytes], len);
Run Code Online (Sandbox Code Playgroud)

我尝试这样将字节转换为 imageView

 const unsigned char *bytes = [imageData bytes];

    NSUInteger length = [imageData length];

    NSMutableArray *byteArray = [NSMutableArray array];

    for (NSUInteger i = 0; i < length; i++) {
        [byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]];
    }
    NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
                              byteArray, @"photo",
                              nil];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJson options:0 error:NULL];
    NSLog(@"");
    UIImage *image1 = [UIImage imageWithData:jsonData];

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];


    imgView.image=image1;
Run Code Online (Sandbox Code Playgroud)

我得到了输出,将图像转换为字节数组,但我想将字节数组转换为图像,所以请帮助我提前感谢。

kuk*_*shi 5

首先,您需要将字节转换为 NSData

NSData *imageData = [NSData dataWithBytes:bytesData length:length];
Run Code Online (Sandbox Code Playgroud)

然后,将数据转换回图像。

UIImage *image = [UIImage imageWithData:imageData];
Run Code Online (Sandbox Code Playgroud)

并且我建议您在出现问题时首先搜索文档。

这是全部:

UIImage *image = [UIImage imageNamed:@"RAC.png"];

NSData *imageData = UIImagePNGRepresentation(image);
// UIImageJPGRepresentation also work

NSInteger length = [imageData length];

Byte *byteData = (Byte*)malloc(length);
memcpy(byteData, [imageData bytes], length);

NSData *newData = [NSData dataWithBytes:byteData length:length];

UIImage *newImage = [UIImage imageWithData:newData];

UIImageView *imageView = [[UIImageView alloc] initWithImage:newImage];
imageView.frame = CGRectMake(50, 50, 100, 100);
[self.view addSubview:imageView];
Run Code Online (Sandbox Code Playgroud)