NSData to byte array (or array of integers) - iphone

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?

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];

Related

objective c - How to convert nsdata to byte array [duplicate]

This question already has answers here:
How to convert NSData to byte array in iPhone?
(6 answers)
Closed 9 years ago.
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.
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?

How to read bytes from NSData

Can anyone suggest a method to read bytes from NSData (like read function in #interface NSInputStream : NSStream)
How to read binary bytes in NSData? may help you:
NSString *path = #"…put the path to your file here…";
NSData * fileData = [NSData dataWithContentsOfFile: path];
const char* fileBytes = (const char*)[fileData bytes];
NSUInteger length = [fileData length];
NSUInteger index;
for (index = 0; index<length; index++) {
char aByte = fileBytes[index];
//Do something with each byte
}
You can also create an NSInputStream from an NSData object, if you need the read interface:
NSData *data = ...;
NSInputStream *readData = [[NSInputStream alloc] initWithData:data];
[readData open];
However, you should be aware that initWithData copies the contents of data.
One of the simplest ways is to use NSData getBytes:range:.
NSData *data = ...;
char buffer[numberOfBytes];
[data getBytes:buffer range:NSMakeRange(position, numberOfBytes)];
where position and length is the position you want to read from in NSData and the length is how many bytes you want to read. No need to copy.
Alex already mentioned NSData getBytes:range: but there is also NSData getBytes:length: which starts from the first byte.
NSData *data = ...;
char buffer[numberOfBytes];
[data getBytes:buffer length:numberOfBytes];
May way of doing that..
do not forget to free byte array after usage.
NSData* dat = //your code
NSLog(#"Receive from Peripheral: %#",dat);
NSUInteger len = [dat length];
Byte *bytedata = (Byte*)malloc(len);
[dat getBytes:bytedata length:len];
int p = 0;
while(p < len)
{
printf("%02x",bytedata[p]);
if(p!=len-1)
{
printf("-");
}//printf("%c",bytedata[p]);
p++;
}
printf("\n");
// byte array manipulation
free(bytedata);

iphone - How do I get the 1st and 2nd byte in a NSData object?

I have a NSData object which is supposed to work like a byte array.
I need to get the 1st and 2nd bytes in the NSData, but don't know how.
If I have a byte array in Java, I can easily get those via barray[0] and barray[1], but how do I do it for NSData?
Thanks
NSData *data = [NSData dataWithBytes:"abc" length:3];
const unsigned char* bytes = [data bytes];
NSLog(#"%c %c",bytes[0],bytes[1]);
You can use this code,
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
now byteData[0] will work.

Convert unsigned char array to NSData and back

How do you convert an unsigned char array to an NSData in objective c?
This is what I am trying to do, but it doesn't work.
Buffer is my unsigned char array.
NSData *data = [NSData dataWithBytes:message length:length];
You can just use this NSData class method
+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length
Something like
NSUInteger size = // some size
unsigned char array[size];
NSData* data = [NSData dataWithBytes:(const void *)array length:sizeof(unsigned char)*size];
You can then get the array back like this (if you know that it is the right data type)
NSUInteger size = [data length] / sizeof(unsigned char);
unsigned char* array = (unsigned char*) [data bytes];

NSString to NSData conversion Problem

I have some Bytes of image in my string and i want to draw it to UIImageView ...Here is my code
NSString* str= #"<89504e47 0d0a1a0a 0000000d 49484452 ........... 454e44ae 426082>";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"My NSDATA %#",data);
imageView.image=[UIImage imageWithData:data];
Now when i saw that printed data on console it is not in same format what i gave to that string..The output is something like.....
<3c383935 30346534 37203064 30613161..........
So my imageview show nothing..... please help
if question was: How to convert string data to image then this is answer.
NSData *imgData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"icon" ofType:#"png"]];
// set your string data into inputString var
NSString *inputString = [imgData description];
NSLog(#"input string %#",inputString);
// clearing string from trashes
NSString *dataStr = [inputString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
// separate by words of 4 bytes
NSArray *words = [dataStr componentsSeparatedByString:#" "];
// calculate number of bytes
NSArray *sizes = [words valueForKey:#"length"];
int sizeOfBytes = 0;
for (NSNumber *size in sizes) {
sizeOfBytes += [size intValue]/2;
}
int bytes[sizeOfBytes];
int counts = 0;
for (NSString *word in words) {
// convert each word from string to int
NSMutableString *ostr = [NSMutableString stringWithCapacity:[word length]];
while ([word length] > 0) {
[ostr appendFormat:#"%#", [word substringFromIndex:[word length] - 2]];
word = [word substringToIndex:[word length] - 2];
}
NSScanner *scaner = [NSScanner scannerWithString:ostr];
unsigned int val;
[scaner scanHexInt:&val];
bytes[counts] = val;
counts++;
}
// get NSData form c array
NSData* data = [NSData dataWithBytes:bytes length:sizeOfBytes];
NSLog(#"My NSDATA %#",data);
// your image is ready
UIImage *image = [UIImage imageWithData:data];
NSLog(#"image: %#",image);
what you are seeing in NSLog output are the ASCII codes of the string characters.
for example:
NSString* str = #"A";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
you will see something like:
<41....
that's because 0x41 is the code for letter A.
Same is happening with your string.
The data is exactly what you're feeding it: a simple string (printed as raw byte values). But I guess your input string is a hexdump and you manually need to turn into bytes.