3

I am working with UIImage conversion to NSData. And I want to convert NsData to Byte Array and post that Byte array to server with the help of json Parser.

If i am passing following type of static string to server it accept and store. Following is just example string syntax. i want follwoing type of byte array to post data to server.

[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,...]

For above result i am converting image to data as following:

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

Now i want to convert NSdata to byte array for that i am using following code:

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

and i also store this to NSdata. but cant get about result. I also typed about code with looping but every time it gives aPNG as result.

Am i doing any thing wrong in the above code?

Please provide me some help and also request to provide any help for this.

Thanks in advance.

8
  • Do you want to convert it to a byte array (in the C sense of the term), or a JSON-encoded string that represents a list of numeric values? Commented Mar 21, 2013 at 18:35
  • Any reason why you're freeing your buffer as soon as you fill it? If you're expecting the buffer to still hold what the NSData object held... you cannot count on it one you free it. Only free it when you no longer need the buffer. Commented Mar 21, 2013 at 18:37
  • @udy thanks for your reply but using that way. it is not working. Commented Mar 21, 2013 at 18:40
  • @zneak i want to convert My NSData to byte array format as i shown in my question. Commented Mar 21, 2013 at 18:42
  • @Hrushikesh Why would you post the data to a server as a list of decimal values? That's pretty inefficient. Why not just post the raw data bytes? Commented Mar 21, 2013 at 18:48

1 Answer 1

10

I'm not 100% sure this is what you are looking for or not. Try:

UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *data = UIImagePNGRepresentation(image);
NSUInteger len = data.length;
uint8_t *bytes = (uint8_t *)[data bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:len * 3];
[result appendString:@"["];
for (NSUInteger i = 0; i < len; i++) {
    if (i) {
        [result appendString:@","];
    }
    [result appendFormat:@"%d", bytes[i]];
}
[result appendString:@"]"];

Is this what you need?

Sign up to request clarification or add additional context in comments.

1 Comment

Minor remark: If you declare bytes as const uint8_t *bytes then you don't need the type cast on the rhs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.