Friday, 24 July 2015

Image to Byte and Byte to Image conversion

In many situations we need to convert image to byte. It is useful in many scenarios because byte arrays can be easily compared, compressed, stored, or converted to other data types.
Here a simple code to convert image to byte array.

//Using image picker for select a image(we can use any specified way for selecting a image).

-(IBAction)openPhotoAlbum:(UIButton *)sender{
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    // Get selected image
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self
convertImageToByte: image];
}
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


//Convert image to byte format
-(void) convertImageToByte:(UIImage *)image{
       NSData *data = UIImagePNGRepresentation(image);
       NSUInteger len = data.length;
       uint8_t *bytes = (uint8_t *)[data bytes];
      NSMutableString *result = [NSMutableString stringWithCapacity:len * 3];
       for (NSUInteger i = 0; i < len; i++) {
        if (i) {
            [result appendString:@","];
        }
        [result appendFormat:@"%d", bytes[i]];
    }
    [result appendString:@"]"];
    NSLog(@"Image in Byte  = %@",result);

}  


//Change byte to UIImage
-(void)convierteImagen: (NSMutableString *)cadenaImagen{
   
    NSArray *strings = [cadenaImagen componentsSeparatedByString:@","];
    unsigned c = strings.count;
    uint8_t *bytes = malloc(sizeof(*bytes) * c);
   
    unsigned i;
    for (i = 0; i < c; i++)
    {
        NSString *str = [strings objectAtIndex:i];
        int byte = [str intValue];
        bytes[i] = (uint8_t)byte;
    }
   
    NSData *data = [NSData dataWithBytes:bytes length:c];

    //get image
    UIImage *image = [UIImage imageWithData:data];
    //Display image on UIImageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 400,   400)];
    imageView.image = image;
    [self.view addSubview:imageView];
}

No comments:

Post a Comment