iosfreak
iosfreak

Reputation: 5238

Annoying error: Corrupt JPEG data: premature end of data segment

This is my last error message before I submit my app to apple (hopefully) and it's driving me crazy. When saving a image to my phone, it corrupts the file. When it tried to open the file, it gives me error Corrupt JPEG data: premature end of data segment and crashes.

Here's my code to save the image:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
[picker.parentViewController dismissModalViewControllerAnimated:NO];

uploadImage = image;
int orient = uploadImage.imageOrientation;
NSString *theOrientation = [NSString stringWithFormat: @"%d", orient];

NSString *latestIDQuery = @"";
NSArray *results = [database executeQuery:@"SELECT * FROM processes ORDER BY id DESC LIMIT 0,1"];   
for (NSDictionary *row in results) {
    latestIDQuery = [row valueForKey:@"id"];
}

int latestID = [latestIDQuery intValue];

int newID = latestID + 1;

NSString *newIDString = [[NSString alloc] initWithFormat:@"%d", newID];
NSString *imageURL = [NSString stringWithFormat:@"Documents/%@_process.jpg",newIDString];

NSLog(@"Saving here... %@", imageURL);

NSString *uploadImagePath = [NSString stringWithFormat:@"%@_process.jpg",newIDString];

NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:imageURL];
NSLog(@"Needs to write something like this: %@", jpgPath);
[UIImageJPEGRepresentation(uploadImage, 1.0) writeToFile:jpgPath atomically:YES];

[database executeNonQuery:@"INSERT INTO processes (image, album, status, orient, ready) VALUES (?, ?, ' In Queue', ?, 'no');", uploadImagePath, selectedID, theOrientation];

TableViewAppDelegate *dataCeter = (TableViewAppDelegate *)[[UIApplication sharedApplication] delegate];
dataCeter.dataSix = nil;
NSString *databaseURL = [NSString stringWithFormat:@"%@_process.jpg",newIDString];
dataCeter.dataSix = databaseURL;

[self showCaption];

}

Is there a better method in saving images so they won't get corrupt? Also, how do you check it a image is corrupt so you it will never crash again? I've heard that the imageData should start with FF d8 and end with d9 ff.. something like that.

Thanks
Coulton

Upvotes: 0

Views: 5252

Answers (1)

mvds
mvds

Reputation: 47104

Your code assumes all goes well, but you should really check some return values and errors. In particular, on iOS you are normally not allowed to write to the home directory. So the file is probably not saved at all.

You should use the documents directory, and verify that the file is written without errors. The writeToFile: call returns a BOOL indicating success.

Upvotes: 2

Related Questions