what's wrong in this initialization - iphone

I want to load uimage with image in path like this
/var/mobile/Applications/429E283A-6E89-4BCE-861F-252C5327F711/Library/Application Support/Students/43y. F./1.2.840.113564.3.1.2.180.0.0.90.20081228203734483950/1.2.840.113564.10.1.226230117146661685815524478531105858244/Thumbnail.bmp
I used the following code
UIImage* theImage = [UIImage imageNamed:ThumbnailPath];
if (theImage !=nil) {
cell.imageView.image = theImage;
}
else {
NSLog(#"Error");
}
where ThumbnailPath is the path
but the uiimage always nil, and I am sure the file exists , can any one please fix it for me
Best regards

UIImage* theImage = [UIImage imageWithContentsOfFile:ThumbnailPath];
if (theImage !=nil) {
cell.imageView.image = theImage;
}
else {
NSLog(#"Error");
}
hope this helps

I dont thing UIImage imageNamed can load from .bmp files..Read this and this SO threads about handling .bmp files in iphone

Refer UIImage class for load image.

How are you getting the value for "ThumbnailPath"
Are you using + pathForResource:ofType:inDirectory: method under NSBundle class.
If not consider using that.
If yes please edit your question and include the part of your code where you set the value for ThumbnailPath.

May Be this can help you
+(UIImage*)getImageFromDocumentDirectoryWithName:(NSString*)imageName
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *aPath= [documentsDir stringByAppendingPathComponent:imageName];
UIImage *myimage=nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:aPath])
{
myimage =[UIImage imageWithContentsOfFile:aPath];
}
return myimage;
}
You can use add this functon in desired class and use it accordingly

Related

Iphone-saving full size image to document directory hangs my app

I am working on an app similar to photo app in iPhone. The flow is I get images through UIImagePickerController. When I use Actual image and further save that image to documents,
My app hangs. I saw on profile tool that allocation goes to 19 to 20 mb. If there is any solution to that.
Getting image from UIImagepicker controller
Saving it to documents.
-(NSString *)saveImageInDocumentsAtPath:(NSNumber *)number
{
NSString *fileName=[NSString stringWithFormat:#"image%#.png",number];
NSString *imagePath= [[NSString alloc] initWithFormat:#"%#/%#", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],fileName];
UIImage *image = self.selectedImage.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:imagePath atomically:YES];
return imagePath;
}
A typical image is going to be around 3Megabytes, if I am not mistaken (depending on the iPhone and its camera). So going from 19 to 20 is not unreasonable. Why you are at 19 to begin with ay be another question. See if you're loading in too many other images, large files etc.
If you use AV Foundation instead of ImagePicker, you have some other options for handling the images.
And you can write the image to the filesystem asynchronously.
This looks like a great opportunity for some error checking in your code.
Why not try this?
-(NSString *)saveImageInDocumentsAtPath:(NSNumber *)number
{
NSString *fileName=[NSString stringWithFormat:#"image%#.png",number];
NSArray * docDirectoryArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if(docDirectoryArray)
{
NSString *imagePath= [[NSString alloc] initWithFormat:#"%#/%#", [docDirectoryArray objectAtIndex:0],fileName];
UIImage *image = self.selectedImage.image;
if(image)
{
NSData *imageData = UIImagePNGRepresentation(image);
if(imageData)
{
BOOL success = [imageData writeToFile:imagePath atomically:YES];
if(success)
{
// only return the image path in the success == YES case
return imagePath;
} else {
NSLog( #"did not save file to %#", imagePath);
}
} else {
NSLog( #"could not get image data out of the image");
}
} else {
NSLog( #"no image selected");
}
}
// you might want to check in the caller to make certain the imagePath is NULL
return NULL;
}

Corrupted Images in document directory

I am fetching URL of the images from the server and converting this images into png format using:
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(img)];
[data1 writeToFile:pngFilePath atomically:YES];
but some of the images are corrupted when i check them after completing the process on simulator.
Hence these images are not displaying on the app wherever needed.
Please see the attached image as some images are corrupted.
Update
I am calling a method in a loop which fetches the images from the server parallel and didFinishLoading I am performing this:
UIImage *img = [UIImage imageWithData:self.data];
NSArray *split = [self.strImageName componentsSeparatedByString:#"/"];
int arrCount=[split count];
NSString *imageName=[split objectAtIndex:arrCount-1];
NSString *docDirec = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath=nil
pngFilePath = [NSString stringWithFormat:#"%#/Thumbs/%#",docDirec,imageName];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(img)];
[data1 writeToFile:pngFilePath atomically:YES];
[self.data release]; //don't need this any more, its in the UIImageView now
self.data=nil;
i have the similar problem
i solved it using the below code
- (void)viewWillDisappear:(BOOL)animated
{
if (self.m_objWebManager != nil)//Webmanager is class for downloading the images as a background thread
{
[self.m_objWebManager cancelCommunication];
[self.m_objWebManager release];
self.m_objWebManager = nil;
}
}

Image storage as byte code locally from XML parsing & display if it is stored Otherwise go for parsing.

I am having an app in which at the time of launcing the app XML parsing is giving Main category from URL like hp, dell, etc...I am displaying it in the Tableview.
Then on click of particular cell i can get the detail of main category means its subcategory like http://www.dealsbell.com/findcoupon.php?store=hp
Here also i am getting data properly after parsing.
But my concern over here is, in ( http://www.dealsbell.com/findcoupon.php?store=hp ) this link i am getting images.
Each particular subcategory will have a same image. So i want to do something like that the image if first time loaded from the URL then it will display image from parsing otherwise i would like to store that image as its byte code in folder / file / in any way in my device on first parsing.
If once the image is stored to the particular way in my device next time when i will go to see the subcategory it will first check this image is stored locally to my device or not.
If yes then it should go to the particular location to fetch this local image & display it to each cell otherwise will parse & display image.
I hope you are getting, what i want to ask.
Please guide me, how can this be possible & what is the way to get result.
If any example or link you can suggest, then it will be more efficient to me.
Thanks in advance.
There are probably two ways to achive this.
Get NSData out of Image and hold that in UserDefaults or database.
Dump image in application folder and pick image from that place.
So whenever you try to load image for subcatogory check at one of place and if present use that. IF in case you have stored image and if any updated image comes,then remove previous copy and store new one.
-(void) SaveImageinDocumentWithName:(UIImage*) aUIImage Name:(NSString*) aName
{
if(aUIImage)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableString* str = [[NSMutableString alloc] initWithCapacity:300];
[str appendString:documentsDirectory];
[str appendString:#"/"];
[str appendString:aName];
NSFileManager *fileManager = [NSFileManager defaultManager];
[UIImagePNGRepresentation(aUIImage) writeToFile:str atomically:YES];
if(str)
{
[str release];
str = nil;
}
if(fileManager)
{
[fileManager release];
fileManager = nil;
}
[pool release];
}
}
-- Getting saved image
-(UIImage*)GetSavedImageWithName:(NSString*) aFileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableString* str = [[NSMutableString alloc] initWithCapacity:300];
[str appendString:documentsDirectory];
[str appendString:#"/"];
[str appendString:aFileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:str];
NSData *dataToWrite = nil;
UIImage* image = nil;
if(!success)
{
}
else
{
image = [[UIImage alloc] initWithContentsOfFile:str];
}
if(dataToWrite)
{
[dataToWrite release];
dataToWrite = nil;
}
if(str)
{
[str release];
str = nil;
}
if(fileManager)
{
[fileManager release];
fileManager = nil;
}
return image;
}
Parse dealsbell.com/wp-content/uploads/mobile/hp.gif and take only hp.gif
NSString *strImage = [NSString stringWithFormat:#"%#",aBook.image];
UIImage* image = [self GetSavedImageWithName:strImage];
if(image) // This means Image exists
{
// Do what you want
}
else
{
NSURL *url4Image = [NSURL URLWithString:strImage];
NSData *data = [NSData dataWithContentsOfURL:url4Image];
if(data != NULL)
{
image =[[UIImage alloc] initWithData:data];
[self SaveImageinDocumentWithName:image Name:strImage]; // save for future ref.
}
else
{
image =[UIImage imageNamed:#"icon.png"];
}
}

Console Error: failed to find PDF header: `%PDF' not found

When I try to print the current screenshot (for an iPad view) I get this weird error in console window:
failed to find PDF header: %PDF not found.
I wonder why this error is fired in console window ? why it's mentioning something related to PDF although I do not use any PDF related stuff in the whole project.
The code Im using to print the screenshot is :
- (IBAction)print:(id)sender {
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//saving the file to documents directory
NSData * imageData = UIImagePNGRepresentation(viewImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"Screenshot.png"];
[imageData writeToFile:documentsDirectory atomically:YES];
NSString *myFilePath = [documentsDirectory stringByAppendingPathComponent:#"Screenshot.png"];
UIImage *screenShot = [UIImage imageWithData:imageData];
NSData *myData = [NSData dataWithData:UIImagePNGRepresentation(screenShot)];
self.pic = [UIPrintInteractionController sharedPrintController];
if (self.pic && [UIPrintInteractionController canPrintData:myData] ) {
self.pic.delegate = self;
//filling up print info
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [myFilePath lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
self.pic.printInfo = printInfo;
self.pic.showsPageRange = YES;
self.pic.printingItem = myData;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
if (!completed && error)
NSLog(#"FAILED! due to error in domain %# with error code %u",
error.domain, error.code);
};
[self.pic presentFromRect:self.printButton.frame inView:self.view animated:YES completionHandler: completionHandler]; // iPad
}
}
The file path (Screenshot.png) is correct, and it is correctly saved to documents directory.
It would help to know which line, exactly, causes that console output. You could step through it in the debugger to find out.
My guess is that it's the call to -[UIPrintInteractionController canPrintData:]. If you read the documentation for that method, you'll see that it has to check if that data contains PDF. It looks like it tries and fails, printing a message along the way.
Since generally no end users watch the iOS console, this is not a very important bug, apparently not important enough for Apple to fix.
This happened to me as well. I checked through every line and I found out that this is because you are printing data. And if you directly print image this weird warning will disappear. Because from Apple's file of the UIPrintInteractionController framework:
#NSCopying public var printingItem: AnyObject? // single NSData, NSURL, UIImage, ALAsset
The printingItem can be any one of the above four types. My guess is Apple takes data as PDF data by default, and apparently, this is no header data in the data you generated from UIImage.

IPhone UIImageView Image

I am trying to set image to UIImageView programmatically but it does't work. I have following code.
[image setImage:[UIImage imageNamed:[self localImagePath:NO]]];
and
-(NSString *)localImagePath:(BOOL)forSave {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES);
NSString *picturesDirectory = [paths objectAtIndex:0];
NSString *picturesPath = [picturesDirectory stringByAppendingPathComponent:#"image.png"];
if (forSave || [[NSFileManager defaultManager] fileExistsAtPath:picturesPath]) {
return picturesPath;
}
else {
return [[NSBundle mainBundle] pathForResource:#"image" ofType:#"png"];
}
}
Is it possible to set image to UIImageView on run time from different mediums?
The imageNamed: method takes only the filename as an argument, not a path. Also it will look for that file in the main bundle only. Try using imageWithContentsOfFile: instead.
You'll have to use two different ways to load the image
[UIImage imageNamed: name] for the resource based one
[UIImage imageWithContentsOfFile: filename] for the one you found locally.
consider changing your method to return the UIImage and use the appropriate loading method internally.
Use [UIImage imageWithContentsOfFile:[self localImagePath:NO]], instead of [UIImage imageNamed:...] for the one you found using your localImagePath method.