Before iOS 8, I didn't have problems with this & now, yes.
LOG:
Assertion failed: (CGFloatIsValid(x) && CGFloatIsValid(y)), function void CGPathMoveToPoint(CGMutablePathRef, const CGAffineTransform *, CGFloat, CGFloat), file Paths/CGPath.cc, line 254.
This is my code:
UIImage* image = nil;
CGSize imageSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
UIGraphicsBeginImageContextWithOptions(imageSize, NO , 0.0f);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; // <- ERROR
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
My purpose is to convert the view to image.
Check for empty rectangles in what you're drawing, whether the view's bounds or the layer's content rectangle. I have noticed that assertion failure on iOS 8 where, before, empty rectangles were silently ignored.
I've added a number of...
if (!CGRectIsEmpty(bounds)) {
}
...conditions in my drawing.
We ran into this problem as well and tracked it down to a view that had a cornerRadius set on the CALayer, but had a zero size. In our case, this was only occurring on a device - not on the simulator. If you see _renderBorderInContext and CA_CGContextAddRoundRect in your backtrace then you're probably seeing the same thing.
A zero size in either dimension (height/width) will cause this error to occur if a corner radius is set. Unfortunately since it's an assertion it's not possible to catch the error and recover, so we're exploring the option of traversing the hierarchy prior to snapshotting to detect the case and recover by setting the cornerRadius to 0 and back after the call to renderInContext.
Works in IOS 8
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
fileName = [docDir stringByAppendingPathComponent:[NSString stringWithFormat:#"reporte.png"]];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSError *error = NULL;
BOOL written =[imageData writeToFile:fileName atomically:YES];
if (!written)
NSLog(#"write failed, error=%#", error);
else{
[self sendPorCorreo];
}
While... I will solve the export of other way.
Regards.
- (IBAction)ibaExportar:(id)sender {
NSString *mystr = #"";
NSString *csvstr;
csvstr = [NSString stringWithFormat:#",Cliente,Domicilio,DueƱo"];
mystr = [NSString stringWithFormat:#"%#,%#,%#\n",self.numCliente,self.iboDomicilio.text,self.iboDueno.text];
csvstr = [NSString stringWithFormat:#"%#\n%#",csvstr,mystr];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
fileName = [docDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Reporte.csv"]];
NSError *error = NULL;
BOOL written = [csvstr writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!written)
NSLog(#"write failed, error=%#", error);
else{
[self sendEmail];
}
}
- (void) sendEmail {
NSString*subject;
subject= [#"Reporte Cliente " stringByAppendingString:#""];
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:subject];
NSData *dataFile = [NSData dataWithContentsOfFile:fileName];
[picker addAttachmentData:dataFile mimeType:#"text/csv" fileName:#"Reporte.csv"];
NSString *emailBody =subject;
[picker setMessageBody:emailBody isHTML:NO];
[self presentViewController:picker animated:YES completion:nil];
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
Check your float with isnan(x) before using with Core Graphics.
According to the answer from tyler, I fix the problem. You can just find out the problematic view in self.view. The ios 8 not allow the zero size view to set the cornerRadius. So you must have a zero size view and set the cornerRadius for it. You can run the following code to find it out and fix it.
- (void)findZeroSizeControlWithSuperView:(UIView *)superView {
[self isProblematicCrotrol:superView];
[superView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[self isProblematicCrotrol:obj];
}];
}
- (BOOL)isProblematicCrotrol:(UIView *)view {
if ((view.frame.size.width == 0 || view.frame.size.height == 0) && view.layer.cornerRadius != 0) {
NSLog(#"this is the problematic view:%#", view);
return YES;
} else {
return NO;
}
}
Related
I am having an interesting little problem using the uiimagepickercontroller and was wondering if anyone has any insight as to what might be happening. Users can take pictures with the camera or pick from the photo library until the cows come home as many times in a row as they like. My issue lies in allowing users to revert back to the original image that shipped with the app. Here is the flow:
Users go the the tableview which shows a thumbnail of the image.
Users navigate to the detail view which shows a larger view of the image.
Users can tap on the image in the detail view to bring up a custom alertcontroller with options to a) use the camera to take a picture, b) use a picture from their library, or c) revert back to the original image.
Users choose either option 'a' or option 'b' to either take a picture or use a picture from the photo library. IF they IMMEDIATELY change their mind about using one of those choices and want to just go back to using the original image, nothing happens! They can snap another picture or choose another image right away, but cannot revert back to the original image right away.
Reverting back to the original image DOES work perfectly when the app has been closed and then opened again. Sometimes it will work if you navigate around to other views within the app and then come back to the detail view where they just added their own image. By why the delay? I've searched around for two weeks but have not found anything resembling my problem or any solutions that help in any way (like reloading the headerview where image is sitting). Any thoughts?
Also I have figured out how to save the image to iCloud by using the documentation but cannot figure out how to retrieve them so there is no code for that. That is entirely different question. The same thing seems to occur even without that code.
Thanks for taking the time to look at this!
Here is some code:
-(void)bookImageTapped:(UIGestureRecognizer *)gesture
{
URBAlertView *changeImageAlertView = [[URBAlertView alloc] initWithTitle:#"Add A New Book Cover Image" message:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Use Camera", #"Open Gallery", #"Use Original Photo", nil];
[changeImageAlertView setHandlerBlock:^(NSInteger buttonIndex, URBAlertView *alertView) {
[self checkPermission];
if (PHAuthorizationStatusAuthorized)
{
if(buttonIndex == 0)
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else
{
NSLog(#"Camera not available");
[alertView hide];
}
}
else if (buttonIndex == 1)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
pickerController.delegate = self;
pickerController.allowsEditing = NO;
pickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:pickerController animated:YES completion:nil];
}];
[alertView hide];
}
else if (buttonIndex == 2)
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self restoreOriginalPhoto];
}];
[alertView hide];
}
else
{
NSLog(#"button 2 cancel");
[alertView hide];
}
}
}];
[changeImageAlertView show];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_book.largeBookImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_book.largeBookImage = [self scaleImage:_book.largeBookImage toSize:CGSizeMake(120, 168)];
_bookImageView.image = _book.largeBookImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"png record saved after using picker!");
}];
}
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
//Create a URL to the local file
NSURL *resourceURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]]];
if (resourceURL)
{
CKAsset *asset = [[CKAsset alloc] initWithFileURL:resourceURL];
//create a record object
CKRecord *bookCover = [[CKRecord alloc] initWithRecordType:#"Bookcover"];
//set the record's fields
bookCover[#"title"] = _book.title;
bookCover[#"bookImage"] = asset;
/* TO SAVE A RECORD */
//get the public database
CKContainer *appContainer = [CKContainer defaultContainer];
CKDatabase *publicDatabase = [appContainer publicCloudDatabase];
[publicDatabase saveRecord:bookCover completionHandler:^(CKRecord *bookCover, NSError *error) {
if (error)
{
//insert error handling
return;
}
//insert succesfully saved record code
NSLog(#"jpg record saved after using picker!");
}];
}
}
else
{
NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
- (UIImage *) scaleImage:(UIImage*)image toSize:(CGSize)newSize
{
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
-(void)restoreOriginalPhoto
{
NSLog(#"restore photo called");
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_book.largeBookImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
Here is the headerview with the imageview:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
_headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 26)];
_headerView.backgroundColor = [UIColor colorWithRed:8/255.0 green:46/255.0 blue:46/255.0 alpha:0.8];
if (section == 0)
{
_headerView.backgroundColor = [UIColor whiteColor];
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake((tableView.frame.size.width - 120)/2, 6, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
UITapGestureRecognizer *bookImageTouched = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(bookImageTapped:)];
bookImageTouched.numberOfTapsRequired = 1;
[_bookImageView addGestureRecognizer:bookImageTouched];
_bookImageView.userInteractionEnabled = YES;
[_headerView addSubview:_bookImageView];
}
I finally figured it out! It seems that I was confusing xcode with my property names. The code ended up much simpler in the end.
In didFinishPickingMediaWithInfo I created a UIImage and then set it to the bookImageView.image. Later, when I wanted to be able to update the image back to the original image, then I could call the bundle asset, _book.largeBookImage. Voila! The image was able to update immediately.
The most pertinent code is posted below.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
_chosenImage = [[UIImage alloc] init];
_chosenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
_bookImageView.image = _chosenImage;
_book.wasNewImageAdded = YES;
_book.originalImageUsed = NO;
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[self saveImage:_chosenImage withFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
}
-(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath
{
if ([[extension lowercaseString] isEqualToString:#"png"])
{
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"png"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else if ([[extension lowercaseString] isEqualToString:#"jpg"] || [[extension lowercaseString] isEqualToString:#"jpeg"])
{
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", imageName, #"jpg"]] options:NSAtomicWrite error:nil];
[self.tableView reloadData];
}
else
{
//NSLog(#"Image Save Failed\nExtension: (%#) is not recognized, use (PNG/JPG)", extension);
}
}
-(void)restoreOriginalPhoto
{
_book.originalImageUsed = YES;
_book.wasNewImageAdded = NO;
_bookImageView.image = _book.largeBookImage;
_backgroundImage.image = _book.largeBookImage;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 0)
{
_bookImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 120, 168)];
_bookImageView.contentMode = UIViewContentModeScaleAspectFit;
_bookImageView.clipsToBounds = YES;
_bookImageView.layer.cornerRadius = 10.0f;
if (_book.wasNewImageAdded)
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [self loadImageWithFileName:_book.bookImageID ofType:#"jpg" inDirectory:documentsDirectory];
_bookImageView.image = image;
}
else
{
_bookImageView.image = _book.largeBookImage;
}
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if(_book.originalImageUsed)
{
_bookImageView.image = _book.largeBookImage;
}
[self.tableView reloadData];
[self.tableView setContentOffset:CGPointZero animated:NO];
}
I can't find anything online about threading loading an image from a device and scrolling smoothly through a tableview. There is one on ray wen about this, but it doesn't really help me for my situation.
Does anybody have any advice or code which would help to allow a tableview to scroll smoothly and load images from the device's temporary directory?
i did exactly as mentioned at tutorial, but with modification for nsoperation subclass
this is methods for fetch
-(void) updateData
{
[self.pendingOperations.downloadQueue addOperationWithBlock:^{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathes = [self recursiveRecordsForResourcesOfType:#[#"png", #"jpeg", #"jpg",#"pdf"] inDirectory:documentsDirectory];
#synchronized (self) {
self.documents = filePathes;
NSLog(#"documents count %#", #([self.documents count]));
}
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.delegate modelDidUpdate:self];
});
}];
}
- (NSArray *)recursiveRecordsForResourcesOfType:(NSArray *)types inDirectory:(NSString *)directoryPath{
NSMutableArray *filePaths = [[NSMutableArray alloc] init];
NSMutableDictionary *typesDic = [NSMutableDictionary dictionary];
for (NSString *type in types)
[typesDic setObject:type forKey:type];
// Enumerators are recursive
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:directoryPath];
NSString *filePath;
while ((filePath = [enumerator nextObject]) != nil){
// If we have the right type of file, add it to the list
// Make sure to prepend the directory path
if([typesDic objectForKey:[filePath pathExtension]]){
//[filePaths addObject:[directoryPath stringByAppendingPathComponent:filePath]];
CURFileRecord *record = [CURFileRecord new];
record.filePath =[directoryPath stringByAppendingPathComponent:filePath];
record.fileName = filePath;
[filePaths addObject:record];
}
}
return filePaths;
}
this is .m for subclass
- (void)main {
// 4
#autoreleasepool {
if (self.isCancelled)
return;
NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:self.fileRecord.filePath];
// self.fileRecord.fileData = fileData;
if (self.isCancelled) {
fileData = nil;
return;
}
if (fileData) {
UIImage *newImage;
if ([[self.fileRecord.filePath pathExtension] isEqualToString:#"pdf"])
{
CGPDFDocumentRef doc = [CURDocumentViewerUtilities MyGetPDFDocumentRef:fileData];
newImage = [CURDocumentViewerUtilities buildThumbnailImage:doc withSize:CGSizeMake(64, 96)];
}
else
{
newImage = [CURDocumentViewerUtilities makePreviewImageFromData:fileData];
}
self.fileRecord.previewImage = newImage;
}
else {
self.fileRecord.failed = YES;
}
fileData = nil;
if (self.isCancelled)
return;
// 5
[(NSObject *)self.delegate performSelectorOnMainThread:#selector(imageDownloaderDidFinish:) withObject:self waitUntilDone:NO];
}
}
With update func i've fetched pathes to proccess, and nsoperation subclass loads images. Works fine with 2000 images in fullhd - smoothly and without any lugs
Is there a way to get the filesize in KB from a UIImage, without getting that image from didFinishPickingMediaWithInfo? The images that are presented are coming from the photo album.
I tried the following code, but this gives the following result: size of image in KB: 0.000000
- (void)setImage:(UIImage *)image
{
_image = image;
self.imageView.image = image;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupView];
self.backgroundColor = [UIColor whiteColor];
panGestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(beingDragged:)];
[self addGestureRecognizer:panGestureRecognizer];
// prepare image view
self.imageView = [[UIImageView alloc]initWithFrame:self.bounds];
self.imageView.clipsToBounds = YES;
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:self.imageView];
NSData *imgData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((_image), 0.5)];
int imageSize = imgData.length;
NSLog(#"size of image in KB: %f ", imageSize/1024.0);
overlayView = [[OverlayView alloc]initWithFrame:CGRectMake(self.frame.size.width/2-100, 0, 100, 100)];
overlayView.alpha = 0;
[self addSubview:overlayView];
}
return self;
}
Here is an example of calculating file sizes of files in your HomeDirectory or Documents:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"yourimagename.png"]
File sie is calculated:
filesize = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] fileSize];
NSLog(#"%lld",filesize);
Before you do that add filesize, you can add it in the .m file
#interface ViewController () {
long long filesize;
}
this will result in bytes, if you are trying to convert those bytes into kb you can use the NSByteCountFormatter and it will take care of all the math for you:
NSByteCountFormatter *sizeFormatter = [[NSByteCountFormatter alloc] init];
sizeFormatter.countStyle = NSByteCountFormatterCountStyleFile;
and then call it like so :
[sizeFormatter stringFromByteCount:filesize]
If the image is not saved on the disk you can calculate the size this way:
NSData *imgData = UIImageJPEGRepresentation(_image, 1);
filesize = [imgData length]; //filesize in this case will be an int not long long so use %d to NSLog it
initWithFrame: runs before setImage: is called, so _image is nil at the time you are doing your calculations. You could move them into the setImage: function...
However, this is a weird way of measuring the size of the image. A JPEG file and what ends up in graphics memory are widely different, so if you are doing it for profiling reasons, this is not going to give you any accurate measurements. If you just want the size on disk, you can simply check that through NSFileManager.
NSInteger imageDataSize = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);
In my project is using maximum 60 images and One of my feature is needs to be an automatically crop all the 60 images in a given Ratio. I'm using the for loop for this implementation.
Inside the for loop contains crop and save the images. It was Implemented. But My app Meets crash in device because of Due to Memory pressure. Please Help Me
for (int ref=0; ref<[_selectedPhotosCollectionthumb count];ref++)
{
UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,biManager.screenSize.height/2,biManager.screenSize.width,biManager.screenSize.height/2)];
[scrollView setDelegate:self];
[scrollView setBackgroundColor:[UIColor clearColor]];
[self addSubview:scrollView];
// scrollView.backgroundColor=[UIColor blueColor];
scrollView.userInteractionEnabled=YES;
scrollView.scrollEnabled=YES;
scrollView.tag=ref;
scrollView.hidden=YES;
[_scrollViews addObject:scrollView];
NSLog(#"%i",[_selectedPhotosCollection count]);
NSMutableArray *arrayCell=[_productCollectionsDict valueForKey:[_selectedPhotosCollection objectAtIndex:ref]];
int heightV=0;
for (int cellIndex=0;cellIndex<[arrayCell count];cellIndex++)
{
PrintCellView *cellObj=[arrayCell objectAtIndex:cellIndex];
if(cellObj.pCount>0)
{
PrintEditCellView *cell;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*100,biManager.screenSize.width,100)];
scrollView.contentSize=CGSizeMake(0,heightV*100+100);
cell.delegate=self;
}
else
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*50,biManager.screenSize.width,50)];
scrollView.contentSize=CGSizeMake(0,heightV*50+50);
cell.delegate=self;
}
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"hh:mm:ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"The Current Time is %#",[dateFormatter stringFromDate:now]);
// NSData *imageData=UIImageJPEGRepresentation(Thumbimage,1.0);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[_selectedPhotosCollection objectAtIndex:ref]];
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
UIImage *image1=[[UIImage alloc]initWithData:data];
cell.productName.text=cellObj.productName.text;
UIImage * image=[self imageByCropping:image1 CropRatio:cell.productName.text];
NSLog(#"CROPPPP");
NSData *imageData= [[NSData alloc] initWithData:UIImageJPEGRepresentation(image,1.0)];
//
NSString* path1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Prydex%i%#.jpg",cellIndex,[dateFormatter stringFromDate:now]]];
NSLog(#"pthhh:%#",path1);
[imageData writeToFile:path1 atomically:YES];
cell.editedImageURL=path1;
NSLog(#"%#,%i",cellObj.productName.text,cellObj.pCount);
[scrollView addSubview:cell];
[cell release];
heightV=heightV+1;
[dateFormatter release];
[image1 release];
// [imageData release];
// [image release];
}
}
//NSLog(#"Scroll Count %i",[_scrollViews count]);
for (UIScrollView *scrollView in _scrollViews)
{
if (scrollView.tag==0)
{
scrollView.hidden=NO;
}
else
{
scrollView.hidden=YES;
}
}
[SVProgressHUD dismiss];
}
Cropping Code
- (UIImage *)imageByCropping:(UIImage *)image CropRatio:(NSString*)ratio
{
CGSize size;
NSArray *array=[ratio componentsSeparatedByString:#"*"];
NSString *productWidth=[array objectAtIndex:0];
NSString *productHeight=[array objectAtIndex:1];
NSLog(#"SIZE:%#,%#",productWidth,productHeight);
NSLog(#"SIZE:%f,%f",image.size.width,image.size.height);
if (image.size.width/[productWidth intValue]>=230)
{
if (image.size.height/[productHeight intValue]>=230) {
size=CGSizeMake([productWidth intValue]*230,[productHeight intValue]*230);
NSLog(#"SIZE Inner:%i,%i",[productWidth intValue],[productHeight intValue]);
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
NSLog(#"crop---->%#",NSStringFromCGSize(size));
double x = (image.size.width - size.width) / 2.0;
double y = (image.size.height - size.height) / 2.0;
CGRect cropRect = CGRectMake(x, y, size.width, size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
The solution might be using recursion:
Create a method that takes an array of images you need to process. Inside the method check if array count is zero.
If it is empty you should return, possibly doing some callback to notify the application your image processing is done.
If the array is not empty, take the first image from the array, do all the processing, then remove the first object from the array and call the same method with the new array missing that element. The call should be kind of
[self performSelector:#selector(methodName:) withObject:imageArray];
All together should look something like this:
- (void)processImages:(NSArray *)images {
if(images.count < 1) {
[self performSelectorOnMainThread:#selector(imageProcessingDone) withObject:nil waitUntilDone:NO];
}
else {
UIImage *toProcess = images[0];
NSMutableArray *newArray = [images mutableCopy];
[newArray removeObjectAtIndex:0];
//do the processing
[self performSelector:#selector(processImages:) withObject:newArray];
}
}
I am opening the camera with UIImagePickerControllerSourceTypeCamera and a custom cameraOverlayView so I can take multiple photos without the "Use Photo" step.
This is working great, but there is a memory leak in the save photo function. Through a lot of debugging and research I have narrowed it down to the UIGraphicsGetImageFromCurrentImageContext function.
Here is a snippet of code where it happens:
UIGraphicsBeginImageContextWithOptions(timestampedImage.frame.size, timestampedImage.opaque, [[UIScreen mainScreen] scale]);
[[timestampedImage layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finalTimestampImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I have scoured the internet and it seems that the UIGraphicsGetImageFromCurrentImageContext() function (quoted from this SO question) "returns a new autoreleased UIImage and points the finalTimestampImage ivar to it. The previously allocated UIImage is never actually released, the variable to it is just repointed to somewhere else."
I've tried so many solutions that have apparently worked for others:
Adding timestampedImage.layer.contents = nil; after UIGraphicsEndImageContext
Adding CGContextRef context = UIGraphicsGetCurrentContext(); and CGContextRelease(context); after UIGraphicsEndImageContext
Wrapping the above snippet in an NSAutoreleasePool
Wrapping the entire saveThisPhoto function in an NSAutoreleasePool
Creating an NSAutoreleasePool when the camera pops up and calling the [pool release] when didReceiveMemoryWarning is called
Closing the camera popup when didReceiveMemoryWarning is called, hoping it will clear the pool
Every possibly combination of the above
Yet everything I try, when I take photos I can see the Memory Utilized rising and not falling when I'm repeatedly taking photos on the device.
Does anyone know how I can release the autorelease object created by UIGraphicsGetImageFromCurrentImageContext?
Alternatively, is there an alternative way to make a UIImage out of an UIImageView?
Edit:
Here are the full functions as requested. There's a lot of extra releasing added in there just to try make sure everything is cleaned up. I have gone through and tested for the memory leak with each code block in saveThisPhoto systematically, and it only occurs when the UIGraphicsGetImageFromCurrentImageContext block (snippet above) is run.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSLog(#"SAVING PHOTO");
[self saveThisPhoto:info];
picker = nil;
[picker release];
info = nil;
[info release];
}
- (void)saveThisPhoto:(NSDictionary *)info {
// Get photo count for filename so we're not overriding photos
int photoCount = 0;
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"photocount"]) {
photoCount= [[[NSUserDefaults standardUserDefaults] objectForKey:#"photocount"] intValue];
photoCount++;
}
[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:#"%d", photoCount] forKey:#"photocount"];
[[NSUserDefaults standardUserDefaults] synchronize];
// Obtaining saving path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"ri_%d.jpg", photoCount];
NSString *fileNameThumb = [NSString stringWithFormat:#"ri_%d_thumb.jpg", photoCount];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSString *imagePathThumb = [documentsDirectory stringByAppendingPathComponent:fileNameThumb];
// Extracting image from the picker and saving it
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
// SAVE TO IPAD AND DB
if ([mediaType isEqualToString:#"public.image"]){
// Get Image
UIImage *editedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
// Figure out image orientation
CGSize resizedSize;
CGSize thumbSize;
if (editedImage.size.height > editedImage.size.width) {
resizedSize = CGSizeMake(480, 640);
thumbSize = CGSizeMake(150, 200);
} else {
resizedSize = CGSizeMake(640, 480);
thumbSize = CGSizeMake(150, 113);
}
// MAKE NORMAL SIZE IMAGE
UIImage *editedImageResized = [editedImage resizedImage:resizedSize interpolationQuality:0.8];
// clean up the one we won't use any more
editedImage = nil;
[editedImage release];
// ADD TIMESTAMP TO IMAGE
// make the view
UIImageView *timestampedImage = [[UIImageView alloc] initWithImage:editedImageResized];
CGRect thisRect = CGRectMake(editedImageResized.size.width - 510, editedImageResized.size.height - 30, 500, 20);
// clean up
editedImageResized = nil;
[editedImageResized release];
// make the label
UILabel *timeLabel = [[UILabel alloc] initWithFrame:thisRect];
timeLabel.textAlignment = UITextAlignmentRight;
timeLabel.textColor = [UIColor yellowColor];
timeLabel.backgroundColor = [UIColor clearColor];
timeLabel.font = [UIFont fontWithName:#"Arial Rounded MT Bold" size:(25.0)];
timeLabel.text = [self getTodaysDateDatabaseFormat];
[timestampedImage addSubview:timeLabel];
// clean up what we won't use any more
timeLabel = nil;
[timeLabel release];
// make UIIMage out of the imageview -- MEMORY LEAK LOOKS LIKE IT IS IN THIS BLOCK
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIGraphicsBeginImageContextWithOptions(timestampedImage.frame.size, timestampedImage.opaque, [[UIScreen mainScreen] scale]);
[[timestampedImage layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finalTimestampImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
timestampedImage.layer.contents = nil;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextRelease(context);
// clean up the one we won't use any more
timestampedImage = nil;
[timestampedImage release];
// SAVE NORMAL SIZE IMAGE TO DOCUMENTS FOLDER
NSData *webDataResized = UIImageJPEGRepresentation(finalTimestampImage, 1.0); // JPG
[webDataResized writeToFile:imagePath atomically:YES];
// clean up the one we won't use any more
finalTimestampImage = nil;
[finalTimestampImage release];
[pool release]; // to get rid of the context image that is stored
// SAVE TO DATABASE
[sqlite executeNonQuery:#"INSERT INTO inspection_images (agentid,groupid,inspectionid,areaid,filename,filenamethumb,filepath,orderid,type) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?) ",
[NSNumber numberWithInt:loggedIn],
[NSNumber numberWithInt:loggedInGroup],
myInspectionID,
[[tableData objectAtIndex:alertDoMe] objectForKey:#"areaid"],
fileName,
fileNameThumb,
documentsDirectory,
[NSNumber numberWithInt:photoCount],
[NSNumber numberWithInt:isPCR]
];
// Clean up
webDataResized = nil;
[webDataResized release];
} else {
NSLog(#">>> IMAGE ***NOT*** SAVED");
}
NSLog(#"IMAGE SAVED - COMPLETE");
info = nil;
[info release];
}
You're setting your variables to nil before releasing them, and some are already auto released.
Normally when using release you should release and them set to nil.
[var release]
var = nil;
But in some of these you should not be calling release.
The following one is your main culprit.
// clean up the one we won't use any more
timestampedImage = nil;
[timestampedImage release];
// SAVE NORMAL SIZE IMAGE TO DOCUMENTS FOLDER