iOS - write jpeg file to file system - ios

I'm new to iOS development and I'm trying to write an image as a jpeg file to the file system. From the logs I know that those file are indeed written to the file system, but when I try to save them to the camera roll they all appear black. I'm using the following code to write them as jpeg files:
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpegPath atomically:YES];
And the following code to write to camera roll:
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
Anybody know how to verify that those jpeg files are indeed written to the file system? And what I might be doing wrong in the second line of code?
EDIT: So here is the entire method:
- (BOOL)createImagesForSlides:(NSString *)documentsPath destinationURL:(NSURL *)destinationURL
{
NSFileManager *manager = [NSFileManager defaultManager];
CPDFDocument *document = [[CPDFDocument alloc] initWithURL:destinationURL];
NSString *folderName = [NSString stringWithFormat:#"/%#", document.title];
// create new folder
NSString *newFolderPath = [documentsPath stringByAppendingString:folderName];
BOOL result = [manager createDirectoryAtPath:newFolderPath withIntermediateDirectories:NO attributes:nil error:nil];
// create a jpeg file for each page of the pdf file
for (int i = 1; i <= document.numberOfPages; ++i) {
NSString *jpegPath = [NSString stringWithFormat:#"%#/%d.jpg", newFolderPath, i];
[UIImageJPEGRepresentation([[document pageForPageNumber:i] image], 1.0) writeToFile:jpegPath atomically:YES];
UIImageWriteToSavedPhotosAlbum([[document pageForPageNumber:i] image], nil, nil, nil);
}
return result;
}
document is a pointer to a CPDFDocument instance, and it's from some open source reader code available on github (iOS-PDF-Reader). What I basically do here is grab each page of the pdf document, generate an image, and then save them to the file system as jpeg file. Weird enough, even though there are more than 10 pages in the document, UIImageWriteToSavedPhotosAlbum only writes 5 files to camera roll. Any idea why?

It would probably be useful to see how you construct jpegPath here.
First, writeToFile:atomically: returns a BOOL, so check that for your first indication of success or failure.
There are a couple of ways you can verify that the image is written to the file system. If you are running on a device use something like iExplorer to access the file system and look at the file written. Since it is NSData* you can cheek the file size to make sure it looks reasonable. On the simulator, dig into the folder structure under ~/Library/Application Support/iPhone Simulator/ and examine the file. Without looking into the filesystem itself try reading the image back into another UIImage (imageWithData: in your case since you are writing a NSData* object).
There doesn't appear to be anything wrong with your UIImageWriteToSavedPhotosAlbum call according to the docs. It is OK for the last 3 arguments to be nil (all are marked as optional), you just have to be sure the UIImage is valid. Have you set a breakpoint to be sure you have a valid image (Xcode Quick Look feature)?

Related

Can't figure out file size on iOS App

I've been checking different solutions that I've found through StackOverflow but sadly I couldn't find the solution to this problem. I basically need to find the size (in bytes, Kb or whatever) to an image that is stored in the iPhone Image gallery. Actually, I need to validate the size before uploading it to a server.
So, I took a JPEG image from the internet:
http://static1.uk.businessinsider.com/image/596c82d34af3fa51058b4978-707/david%20slater.jpeg
Once I download this to my computer, when i get the file information it says:
Size 80865 bytes (82 KB on disk). So, I save this file to the iPhone's image library. Once I get the image from the gallery and I inspect it through xCode I see the following:
So, basically the file has 80865 bytes when it's on my computers disk, but it has 289371 when I inspect it through xcode (the method length from the NSData object returns 'the number of bytes contained by the data object' according to the documentation). Am I missing something? Why is the image inside the iPhone disk almost 4 times the size of the image stored in the iPhone?
The code I am using is:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSUInteger length = [UIImageJPEGRepresentation(image,1.0f) length];
}
EDIT: Ok, so I've changed the code to save the image to disk first and check the size then, I use:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];
[UIImageJPEGRepresentation(image,1.0f) writeToFile:filePath atomically:YES];
NSError *attributesError;
NSDictionary*fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
}
So, If i print the value of the variable fileSizeNumber I get: 369055 (which according to the documentation indicated the file's size in bytes). But this number doesn't seem to match the original 80865 either, it is actually 10 times bigger than the original image!
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
You're writing the uncompressed data (or at least differently compressed data) to a file and then checking its length. But the point the JPEG file format is that it compresses the data. It's not surprising that reading a JPEG image, writing it to a file as PNG data, and then looking at the length of that file doesn't tell you what you want.
I'm not sure why you don't believe what Xcode is telling you, but if you feel driven to see the actual size of the JPEG image in its compressed state, you'll need to find the JPEG file itself. You'd do something like:
[[NSBundle mainBundle] pathForResource:#"selfie" ofType:#"jpeg"];
to get a path to the file, and then use NSFileManager to look at the attributes of the file at that path.

How would I go about saving snaps (UIImage) to the sandbox?

I'm creating a Theos tweak for my jailbroken iPhone and I'm stuck on a feature. So far I can block screenshot detection and replay detection, add infinite text, and have the app open directly to the feed. The feature I'm stuck on is saving incoming and outgoing snaps (and stories, but one step at a time). I used the FLEXible tweak from Cydia to assist me and I noticed that the snaps have something to do with "UIImage." From what I know I have to somehow convert this UIImage to *.jpg or *.png and save it somewhere (I'm looking to save it to the app's Documents directory).
I searched around the site and found the following that may be helpful:
// Convert UIImage to JPEG
NSData *imgData = UIImageJPEGRepresentation(image, 1); // 1 is compression quality
// Identify the home directory and file name
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.jpg"];
// Write the file. Choose YES atomically to enforce an all or none write. Use the NO flag if partially written files are okay which can occur in cases of corruption
[imgData writeToFile:jpgPath atomically:YES];
and
// Create paths to output images
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.png"];
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.jpg"];
// Write a UIImage to JPEG with minimum compression (best quality)
// The value 'image' must be a UIImage object
// The value '1.0' represents image compression quality as value from 0.0 to 1.0
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];
// Write image to PNG
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
(like I said I found this; it is not my code).
Bah, I'm not sure how I would incorporate this. Any help?

IOS Memory Management - writing video to temp file

I'm creating an app that plays back multiple videos and photos in a snapchat story fashion. I fetch each of these videos data and write it to a temp file in order to play with AVPlayer.
NSString *outputPath = [[NSString alloc] initWithFormat:#"%#%#", NSTemporaryDirectory(), [NSString stringWithFormat:#"output%i.mov", i]];
[data writeToFile:outputPath atomically:YES];
In viewWillDissapear I delete all of these files with:
NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
for (NSString *file in tmpDirectory) {
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:#"%#%#", NSTemporaryDirectory(), file] error:NULL];
}
But when I look at how much memory my app is using, in settings, its around 300 mb. Is there a way to see what is actually taking up all this memory? I would think this is high since I'm not caching anything besides the currentUser data (name, profileImage).
Should I be doing something else to clean the temp files?
But this line is absolutely wrong:
[data writeToFile:outputPath atomically:YES];
The implication is that at some moment — this moment — you are holding an entire video in memory (as data). That is completely incorrect; it should never happen. You should download to a file on disk, and if necessary, write that file to another file; you should never attempt to load the entire video into memory at once.
As #peter mentioned, you can use streaming Video streaming.
Or else If you really want to download video file and store it into the disk space and want to utilize it later part then you should follow apple recommended way i.e NSFileHandle class to optimize your application heap memory while downloading larger files.
NSFileHandle

Terminated due to memory error iOS?

I am working on a project where I need to manage videos. I need to rename or delete video. For that we need to hold the video in NSDATA and then manage it.
But I am getting an error message as Terminated due to memory error on below statement.
Edited
NSData *data=[NSData dataWithContentsOfFile:self.path];
if (data){
BOOL success = [data writeToFile:videopath atomically:NO];
}
self.path contains the path of video file. It works in small size video (of 4-10 mins) But it crashes in large size video (bigger than 20-30 mins).
Please advice.
Use this code instead loading the video file to memory, Your code will work with small files but u gonna fail with big files.
if ( [[NSFileManager defaultManager] isReadableFileAtPath:source] ){
[[NSFileManager defaultManager] copyItemAtURL:source toURL:destination error:nil];}
You are maintaing the full video as NSData inside the application. Instead of using a Video file as NSData, copy the video to some where (e.g NSTempoaryDirectoy). You can delete or rename the Old video.
I am not sure what the requirement for you. from your question I understood that you need to rename your video file. for renaming, why we need to go for reading it as NSdata and again writing the same. for Renaming try the below code.
NSFileManager *filemanager = [NSFileManager defaultManager];
if ([filemanager fileExistsAtPath:filePath])
{
NSString *target = [[filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newnameofthefile];
[filemanager moveItemAtPath:filePath toPath:target error:nil];
}
I hope this may help you..

Converting an iPhone IOS Video File Uploader to work with a file stored in document directory

This is my first real project. I have an app that captures several seconds of video using AVFoundation, outputs this to a file in the documents directory and lets the user preview the video before they upload it using HTTP and a PHP script on my website.
All the video capture and preview work perfectly but I am stuck on uploading the video file.
I learnt a lot from this simpleSDK video which shows how to achieve the desired effect using a video file stored in the apps main bundle.
The code from the tutorial that set up videoData ready to upload originally looked like this:
NSData *videoData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Movie" ofType:#"mov"]];
NSString *urlString = #"http://www.iphonedevnation.com/video-tutorial/upload.php";
The filename of the video file that I need to upload is always unique and generated using CFUUIDCreateString. I join this string to the path for the documents directory, add ".mov" to the end of it and save it into a text file for retrieving later.
This all works as I am able to retrieve the filename from the file and use it to preview the movie clip elsewhere in the app.
My path is in an NSString, that I have tried converting to NSURL and removing the file suffix to get it to work with the NSData *videoData.........line but it doesn't compile, I get an "No known class method for selector 'dataWithContentsOfFile:ofType.' error. I am targeting iOS 5 and using Xcode 4.3 with ARC and Storyboards.
I've been at this for best part of 5 hours now so hopefully someone can help. My code, which included tips from elsewhere on converting from a NSString to NSURL follows:
NSString *content = [[NSString alloc] initWithContentsOfFile:lastSavedTalentFilenamePath
usedEncoding:nil
error:nil];
NSLog(#"content=%#",content);
//Need to now remove the '.mov' file type identifier
NSString *shortContent= [content substringToIndex:[content length]-4];
NSLog(#"***************shortContent***************%#", shortContent);
NSURL *convertedContent = [NSURL fileURLWithPath:shortContent];
NSLog(#"***************convertedContent***********%#",convertedContent);
NSData *videoData = [NSData dataWithContentsOfFile:convertedContent ofType:#"mov"];];
There is no NSData method called dataWithContentsOfFile:ofType:
The methods available are:
+ dataWithContentsOfFile:
+ dataWithContentsOfFile:options:error:
both of which take the file location as an NSString so there's not need to convert to an NSURL

Resources