2

I am working with a webservice which gives me an image as an array of integers. I have managed to convert this array into an NSData object and then into a UIImage using the code below. Now I am in doubt how I will convert an image into a similar array.

The array looks like this:

[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,219,0,67,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,...]

This is the code I use to convert the above array to a UIImage.

+ (UIImage *)imageFromBytes:(NSArray *)bytes
{
    unsigned char *buffer = (unsigned char *) malloc(bytes.count);
    int i = 0;
    for (NSDecimalNumber *num in bytes)
        buffer[i++] = num.intValue;
    NSData *data = [NSData dataWithBytes:buffer length:bytes.count];
    free(buffer);

    return [UIImage imageWithData:data];
}

So, I need to convert a UIImage into an array of integers (a byte array).

Can anybody point me in the right direction?

1 Answer 1

1

You can get the data for an image with:

UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *data = UIImagePNGRepresentation(image);

If you use a JPG you can use UIImageJPEGRepresentation.

And then, extract the array of bytes:

NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
free(byteData)

You can use also the method (void)getBytes:(void *)buffer length:(NSUInteger)length from NSData:

[data getBytes:&byteData length:len];
Sign up to request clarification or add additional context in comments.

1 Comment

The bytes received from getBytes - are they raw bytes that can be understood by java and formed back into the image or are they the bytes of the NSData object (which will subsequently be decoded into another NSData object and thus not be understood by java)...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.