Making an UIImage from byte string - arrays

I am paring a XML and getting an image in Byte form and I have put that in a string. Now I have to draw that image.
I have tried to use various methods but no success. How can I do this?

Try converting the string to NSData:
NSString* str= ....
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
Then take a look at:
UIImage *image = [[UIImage alloc] initWithData:data];
Hope this helps.

You can convert the byte into NSData and then you can get the image using
UIImage *image = [[UIImage alloc] initWithData:data];
OR
UIImage *image = [UIImage imageWithData:data];

Related

Call an array from object

-(NSMutableArray *) botanicalPlant {
if (_botanicalPlant == nil) {
_botanicalPlant = [[NSMutableArray alloc] initWithObjects:#"Abelia", nil];
}
return _botanicalPlant;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.botanicalPlantName = [[BotanicalPlant alloc] init];
self.botanicalPlantNameLabel.text = []
}
I know this may be a simple question but Im stuck on this one. I have an array in NSObject of Botanical I just don't know how to call it in the viewDidLoad method for it to show up in my main view controller. I don't know what to put in the brackets to assign it to the text of the label.
You haven't shown enough code to answer your question for sure. But if botanicalPlant is a mutable array property on the BotanicalPlant class, then you could do something like:
BotanicalPlant *myBotanicalPlant = [[BotanicalPlant alloc] init];
NSMutableArray *namesArray = myBotanicalPlant.botanicalPlant;
self.botanicalPlantNameLabel.text = [namesArray firstObject];
Try This:
In your viewDidLoad method
NSMutableArray *arrayFromBotanicalMethod = [self botanicalPlant];
// Then set the text label from your new array that you created
self.botanicalPlantNameLabel.text = [arrayFromBotanicalMethod objectAtIndex:0];
This code is based on the limited information you provided. You basically create another array that will hold the returned array from your botanicalPlant method. Then you use the objectAtIndex message on the new array to get the text for the label.
Hope it helps.

strange behavior with postNotificationName with NSDictionary in userInfo

I'm trying to debug a strange problem I'm seeing when passing a NSDictionary as my userInfo in NSNotification using ARC on ios 6. Here's my relevant code:
to send the notification:
NSDictionary *feedData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
NSDictionary* finalData = [[NSDictionary alloc] initWithObjectsAndKeys:#"index", [NSNumber numberWithInt:i], #"myKey", feedData, nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"myNotification" object: nil userInfo:finalData];
my handler registration:
[[NSNotificationCenter defaultCenter] addObserver:frcvc selector:#selector(mySelector:) name:#"myNotification" object:NULL];
my handler declaration:
-(void)mySelector:(NSNotification*)notification;
my handler definition which is inside my MyCollectionViewController class:
- (void)mySelector:(NSNotification*) notification
{
NSDictionary* myDict = (NSDictionary*)notification.userInfo;
int index = [[myDict objectForKey:#"index"] integerValue];
NSDictionary* myFeed = (NSDictionary*)[myDict objectForKey:#"myKey"];
}
When I run the code, I can see finalData being constructed, and I make note of the memory address. When I get to my callback and extract userInfo, it is the same memory address, but xcode seems to think it is of type MyCollectionViewController*. And when I try to access index or myFeed, it is null. But in my output window, I can type
"p myDict"
and it correctly shows NSDictionary* with the same memory address as when constructed! And if I type
"po myDict"
it shows the correct dictionary keys and values! What is going on?! I've tried rebuilding clean, but that didn't help. The memory seems to be fine, since I'm getting the correct address and can seem to access it in the debug window. Thanks for any help!
Your objects and keys are in the wrong order:
NSDictionary* finalData = [[NSDictionary alloc] initWithObjectsAndKeys:#"index", [NSNumber numberWithInt:i], #"myKey", feedData, nil];
It should be:
NSDictionary* finalData = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:i], #"index", feedData, #"myKey", nil];
Or even better, using Objective-C Literals:
NSDictionary* finalData = #{#"index": [NSNumber numberWithInt:i], #"myKey": feedData};

Is this an appropriate way of implementing an array of NSImages?

I have a series of images that I want to make use of in an app. What I wanted to do is store them in an NSArray for easy identification within the drawRect: function.
I have created a .plist file, which details an NSDictionary with the keys simply ascending integer values, and the values corresponding to the image file names. This allows me to iterate through the dictionary and add a series of NSImage objects into the array. I am using a for loop here because the order is important and fast enumeration does not guarantee order of execution when reading from a dictionary!
Currently I am doing the following: (This is in a Subclass of NSView)
#property (strong) NSDictionary *imageNamesDict;
#property (strong) NSMutableArray *imageArray;
...
// in init method:
_imageNamesDict = [[NSDictionary alloc] initWithContentsOfFile:#"imageNames.plist"];
_imageArray = [[NSMutableArray alloc] initWithCapacity:[_imageNamesDict count]];
for (int i=0; i<_imageNamesDict.count; i++) {
NSString *key = [NSString stringWithFormat:#"%d", i];
[_imageArray addObject:[NSImage imageNamed:[_imageNamesDict objectForKey:key]];
}
// When I want to draw a particular image in drawRect:
int imageToDraw = 1;
// Get a pointer to the necessary image:
NSImage *theImage = [_imageArray objectAtIndex:imageToDraw];
// Draw the image
NSRect theRect = NSMakeRect (100,100, 0, 0);
[theImage drawInRect:theRect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
This all appears to work properly, but with one quirk. I have noticed a small amount of lag that happens in drawing the display, but only when drawing a new image for the first time. Once each image has been seen at least once, I can re-draw any desired image with no lag whatsoever.
Is it that I am not loading the images properly, or is there some way that I can pre-cache each image when I create the objects to add to the for loop?
Thanks!
Assuming you have overcome the "... NSMutableDictionary instead of an NSMutableArray ..." problem pointed out in the comments, you are loading the images properly.
The lag you are describing is because [NSImage imageNamed: ] doesn't do all the work required to draw the image, so that is happening on your first draw.
You could probably get rid of the lag by drawing the images into an offscreen buffer as you add them to your array, something like:
// Create an offscreen buffer to draw in.
newImage = [[NSImage alloc] initWithSize:imageRect.size];
[newImage lockFocus];
for (int i=0; i<_imageNamesDict.count; i++) {
NSString *key = [NSString stringWithFormat:#"%d", i];
NSImage *theImage = [NSImage imageNamed:[_imageNamesDict objectForKey:key]];
[_imageArray addObject: theImage];
[theImage drawInRect:imageRect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
}
[newImage unlockFocus];
[newImage release];

UIImage initWithContentsOfFile:... - need to get only dimensions

I need to get only width and height from PNG file. Is it possible to do with UIImage? The reason is because sometimes (in rare cases with some images with odd width and RGB8 format) UIImage returns different dimension than libpng).
I have found an answer here: http://oleb.net/blog/2011/09/accessing-image-properties-without-loading-the-image-into-memory/
#import <ImageIO/ImageIO.h>
NSURL *imageFileURL = [NSURL fileURLWithPath:...];
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);
if (imageSource == NULL) {
// Error loading image
...
return;
}
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], (NSString *)kCGImageSourceShouldCache,
nil];
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, (CFDictionaryRef)options);
if (imageProperties) {
NSNumber *width = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
NSNumber *height = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
NSLog(#"Image dimensions: %# x %# px", width, height);
CFRelease(imageProperties);
}
We can access any metadata from file without loading an image.

How to copy the NSString JSON in to NSDictionary?

Actually in getting JSON data from a sql server in a encypted format and i decrypt the json data and stored in a NSString. So i have to copy the stored json string to a NSDictionary. So that i can able to call each and every data using valueForKeys.
NSString *requestMode = #"Hello buddy";
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://funsip.com/interaction_demo.php?requestMode=LIBRARY&categoryid=3"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[requestMode dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *err = nil;
NSHTTPURLResponse* response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err ];
if (err != nil) { NSLog(#"Failed"); }
NSString* answernew = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding]; `
so i want to copy the ansernew string to a NSDictionary.
Thanks in advance
K.Karthik
If you are targetting iOS 5.0, you can use NSJSONSerialization to parse the data:
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
You don't have to convert data to a string first.
You'll need JSONkit for that.

Resources