Sunday, 11 January 2015

iOS-Convert UIImage to Byte Array and vice versa



 //Convert UIImage to Byte Array


UIImage*imageOBJ;
if (imageOBJ) {       

 NSData *data = UIImagePNGRepresentation([[assist shared] getTranferImage]);

NSUInteger len = data.length;
        uint8_t *bytes = (uint8_t *)[data bytes];NSMutableString *result1 = [NSMutableString  stringWithCapacity:len * 3];

        for (NSUInteger i = 0; i < len; i++) {
            if (i) {
                [result1 appendString:@","];
            }
            [result1 appendFormat:@"%d", bytes[i]];
        }
       
        NSArray*arr=[result1 componentsSeparatedByString:@","];
        [dictnew setObject:arr forKey:@"Picture"];
    }

 //Convert Byte Array to UIImage

 NSArray* bytedata = [self.trans valueForKey:@"Picture"];
        unsigned c = bytedata.count;
        uint8_t *bytes = malloc(sizeof(*bytes) * c);
       
        unsigned i;
        for (i = 0; i < c; i++)
        {
            NSString *str = [bytedata objectAtIndex:i];
            int byte = [str intValue];
            bytes[i] = (uint8_t)byte;
        }
       
        NSData *datos = [NSData dataWithBytes:bytes length:c];
       
        imgTran=[[UIImageView alloc]initWithFrame:CGRectMake(5, 240, 150, 160)];
        [imgTran setImage:[UIImage imageWithData:datos]];  


1 comment:


  1. imgData is Array of bytes converted to string, I have tried using the above but I am getting image as null
    NSArray *strings = [imgData componentsSeparatedByString:@"-"];
    NSLog(@" %@", strings);

    int count = (int)[strings count];
    uint8_t *buffer;
    buffer = (uint8_t *) malloc (sizeof(*buffer) * count) ;
    unsigned i;
    for (i = 0; i < count; i++)
    {
    NSString *str = [strings objectAtIndex:i];
    int byte = [str intValue];
    buffer[i] = (uint8_t)byte;
    }

    // NSData *imageData = [NSData dataWithBytesNoCopy:buffer length:count freeWhenDone:YES];
    NSData *datos = [NSData dataWithBytes:buffer length:count];
    UIImage *image = [UIImage imageWithData:datos];
    NSLog(@"image %@", image);

    ReplyDelete