how to convert byte array to image in ios

后端 未结 2 1797
猫巷女王i
猫巷女王i 2021-01-25 03:37

today my task is convert byte array to image

First I try to convert image to byte array :-

For converting Image to Byte array first we have to do is to convert

相关标签:
2条回答
  • 2021-01-25 03:51

    First, you need to convert bytes to NSData

    NSData *imageData = [NSData dataWithBytes:bytesData length:length];
    

    Then, convert the data back to image.

    UIImage *image = [UIImage imageWithData:imageData];
    

    And I suggest you should first searching about the documentations when problems occur.

    Here is all:

    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];
    
    0 讨论(0)
  • 2021-01-25 04:06

    You are representing the data with wrong format

    Your image is of format jpg and you are representing with PNG data.

    For jpg or jpeg format you should use UIImageJPEGRepresentation

    NSData * UIImageJPEGRepresentation (
       UIImage *image,
       CGFloat compressionQuality
    );
    

    The required statement will be

    NSData *imageData = UIImageJPEGRepresentation(image, 0.0f);// Set Compression quality to 0.0. You can change it.
    

    For png format you should use UIImagePNGRepresentation

    NSData * UIImagePNGRepresentation (
       UIImage *image
    );
    

    The required statement will be

    NSData *imageData = UIImagePNGRepresentation(image);
    

    To convert the NSData back to UIImage, use

    UIImage *image = [UIImage imageWithData:imageData];
    

    READ THE APPLE DOCS. SEE UNDER IMAGE MANIPULATION

    0 讨论(0)
提交回复
热议问题