I'm trying to save a UIImageView image to a png file, and then use that file as a GLTexture.
I'm having trouble with this, when I try to run my code in the simulator, Xcode says it succeeded, but the simulator crashes with no error messages.
Here is my code:
NSString *dataFilePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Picture.png"];
NSData *imageData = UIImagePNGRepresentation(imageView.image);
[imageData writeToFile:dataFilePath atomically:YES];
// Load image into texture
loadTexture("Picture.png", &Input, &renderer);
Judging by your reply to Metalmi, it looks like you're not giving us the actual code you're compiling. If you're actually doing what it looks like you're doing, then you're trying to write data to your application's bundle, which is going to fail because you're not allowed to do that. Can you provide us with the exact code you're trying to execute?
Try this:
NSString *dataFilePath = [[NSBundle mainBundle] pathForResource:#"Picture" ofType:#"png"];
Related
I'm trying to download an image from the internet. I'm not sure why this code is not working when I want to get the photos with these specs (209x209 pixels,not more than 65KB).
Writing to iPhone directory:
NSData *imgAsData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
//UIImage *image = [UIImage imageWithData:[NSData thumnail_url]];
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:self.product.img_url];
[myFileHandle writeData:UIImagePNGRepresentation(image)];
[myFileHandle closeFile];
I even tried writeToFile, but it still doesn't work.
[imgAsData writeToURL: [NSURL URLWithString:self.product.img_url] atomically:YES];
Reading from iPhone directory:
NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:self.product.img_url];
//NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:self.product.thumbnail_url];
UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
I was using this code in the same app to download thumbnails and they are working (notice the commented out lines using the "thumbnail_url"). I tried to substitute the thumbnail url in the place of this "larger" image and it worked. I was able to save the thumbnail offline, but I need to get the larger version (since, of course, the thumbnails are too pixelated).
I'm sure that the paths are ok since I got the thumnails working.
I'm lost. Is this not working because the file size is "larger"? Help please, Thanks!
The problem is NSFileHandle fileHandleForWritingAtPath can not create a file. You need to create the file first.
To save images to iPhone simply use
UIImageWriteToSavedPhotosAlbum(<#UIImage *image#>, <#id completionTarget#>, <#SEL completionSelector#>, <#void *contextInfo#>)
If you want to save images only 209*209 then add a check before that on the dimension of an image. I don't know(yet) how to read the images from iPhone, but you can use UIImagePickerController to choose the images.
Hope it helps
In my app I need to search images from google images for a particular word.
for example, i want to search image for Earth.
How to search images from Google Images and save selected images in documents directory?
Is there any API that can I use? Or any other way to do it?
Google API
Google Image Search API / JSON Developer's Guide.
You will have to display the images yourself as the result is a json response. However this will give you maximum control. The result will contain a thumbnail URL which you can use to show the preview.
Downloading images
Downloading images can be done in many ways:
URL Loading System Programming Guide / Using NSURLConnection
ASIHTTPRequest
NSData class method dataWithContentsOfURL and usage of the UIImage method imageWithData:
The use of the Google API does only work under certain circumstances such as
"Applications that use this interface must abide by all existing Terms of Service. Most importantly, you must correctly identify yourself in your requests."
Saving Images
After receiving the results you can save the image to disk with:
NSString *aFileName = #"myImage.jpg";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *path = [documentDirectory stringByAppendingPathComponent:aFileName];
[myImageAsData writeToFile:path atomically:YES];
alternatively if you've got the image as UIImage already:
NSData *myImageAsData = [NSData dataWithData:UIImagePNGRepresentation(anImage)];
[myImageAsData writeToFile:path atomically:YES];
First, you want the Google Image Search API. http://code.google.com/apis/imagesearch/
Next, if you're cool with only targeting iOS 4.0 and later, you can use Grand Central Dispatch and the very useful sycnhronous data APIs included in iOS. Specifically, I'm thinking of [NSData dataWithContentsOfURL:]. This will block the thread until it downloads the whole image, so don't run it on the main thread. Fortunately, GCD lets you throw stuff on a background thread with ease. So your code will probably look something like this:
dispatch_queue_t NetworkQueue = dispatch_queue_create("NetworkQueue", 0);
dispatch_async(NetworkQueue,^{
NSData* imageResultsData = [NSData dataWithContentsOfURL:
[NSURL urlWithString:#"https://ajax.googleapis.com/ajax/services/search/images?some_images_query_here"];
//do something with that data
//let's say you unpacked it into an NSArray of NSURLs
for(NSURL* url in myImageArray) {
dispatch_async(NetworkQueue,^{
NSData* imageData = [NSData dataWithContentsOfURL:url];
[imageData writeToFile:file_name_here atomically:YES];
});
}
});
Google Image Search is not working:
"The Google Image Search API has been officially deprecated as of May
26, 2011. It will continue to work as per our deprecation policy, but
the number of requests you may make per day may be limited. We
encourage you to use the Custom Search API, which now supports image
search."
Here is the link to the Custom Search API
I am creating an app in which i am displaying images from photo library and app bundle by clicking on two separate action buttons.
Now what i want is that i want to create a new action button and its purpose will be to select an image from photo library and then save that image into my app bundle.
Can anyone guide me to right direction regarding this topic.
Thanks,
Christy
I don't think you can modify the application bundle once it's on the iPhone. The entire thing is code signed, and changing it would cause it to not run any more. You can try saving the image to documents directory.
So far as I know you cannot repackage the bundles on the iPhone once your app has been released to the App Store. So go the other way, and put the data from the bundle on the filesystem so you can change it at runtime.
My usual technique for this stuff is:
bundle up the initial data
have a routine that checks for the
presence of a versioned file on the
iPhone's filesystem at startup
if that routine doesn't find the
current version of the file, copy
all the data into the iPhone's
filesystem
reference the data from the
filesystem in my app, rather than
using the bundle path
So, essentially your bundle is just a delivery mechanism, a way to preload the filesystem with the stuff you are going to need. Once it's on the filesystem you can change anything you wish.
References
Downloading image into bundle?
How to save a UIImage to the application's Bundle?
UPDATE
- (IBAction)saveImage:(UIImage *)image {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
NSData *imageData = UIImagePNGRepresentation(image);// Change according to your needs
[imageData writeToFile:savedImagePath atomically:NO];
}
You can make an NSData from the image you are picking from your photo library by using this -
NSData *imageData = UIImageJPEGRepresentation (UIImage *image,CGFloat compressionQuality);
then call
[imageData writeToFile:imgPath atomically:YES];
Here imgPath is the path for TMP dirextory where you want to write the file, get it as -
NSString *filename = #"a.png";
NSString *uniquePath = [TMP stringByAppendingPathComponent:filename];
and TMP is an enum
#define TMP NSTemporaryDirectory()
Using MontoTouch for .NET C# iPhone development. (though should not matter)
In the iPhoneSimulator, I use UIImage.FromFile (#"images/Bahai.png"); to get the Bahai.png from the images folder.
However, when I run it in debug mode on my iTouch, the function returns a null.
Only if I put the image file in the root does it work in the iTouch.
Is there a different relative path I need to use?
Ian
Not sure if this will help, but in objective-C, I would load an image from the app bundle like this:
UIImage *image = [UIImaged imageNamed:#"Bahai.png"];
For other types of files, I would get the absolute path like this:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Bahai" ofType:#"png"];
I am writing an application and part of it is recording and playing the sound using AVAudioRecorder and AVAudioPlayer class. I set up the sound file as below.
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:#"/sound.caf"];
self.soundFileURL = [NSURL fileURLWithPath:resourcePath];
When i run the app in simulator, it works fine.However when i load the app into the device it does not work.Does anyone have any idea what the problem could be.
Hi coob. i tried with your answer .But no sound in device .It works in simulator. When i tested in distribution device i got a crash report "unknown kernal[0]:ERROR:AMC reset[non-fatal error]:could not lock BSU "
I don't think you can write to the resourcePath on the device, it's protected. Find the App's documents directory and write somewhere there:
NSArray *filePaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *recordingDirectory = [filePaths objectAtIndex: 0];
NSString *resourcePath = [recordingDirectory stringByAppendingString:#"/sound.caf"];
self.soundFileURL = [NSURL fileURLWithPath:resourcePath];
Is it possible that you have done the same thing that I did the first time I tried to get sound to work on an iPhone? Is the sound muted?
Another possibility:
I have discovered that filenames within the bundle are case-sensitive on the device but not in the simulator. (Or more case-sensitive -- I haven't experimented with exactly what works on each.) So if the case is wrong on a file, it may simply be sliding through on the simulator, but returning nil instead of the file when it runs on the device.
I know, it sounds odd, but I just confirmed it in my own project. Try taking a file that you know loads properly, change the case of the filename, and see how it works on the device. -- clarification -- change the case of the name by which you retrieve the file so it no longer matches the filename within the bundle.
Doesn't mean that's your problem, but something to watch out for nonetheless.
I just reviewed some of my code. Matching your intentions, I come up with:
NSString *soundName = #"sound"; // without extension -- mimicing your naming
NSString *resourcePath = [[NSBundle mainBundle] pathForResource: soundName ofType: #"caf"]]
self.soundFileURL = [NSURL fileURLWithPath:resourcePath];
Does that work?
Make sure your device is not in Silent Mode. Short sounds don't work in silent mode.
I had the same problem I add Audiosession then it is works fine.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
Hope this will work.