Is there a chance, to check if a file in “documents” Directory is a png image?
My App downloads some PNG Files from a server. The App then renders a grayscale image from the PNG. If there went something wrong on the server-side or in the communication, and the png-file is corrupt or no PNG file, the grayscale rendering crashes my whole app.
All i do for now is loading the file from Documents directory into a UIImage Object via:
UIImage *myImage = [[UIImage alloc] initWithContentsOfFile:[myobject.localFolder stringByAppendingPathComponent:@"thumbnail.png"]]
Then i call the method to convert the Image to grayscale with this UIImage.
This is the function i use to render the grayscale image:
- (UIImage *)convertImageToGrayScale:(UIImage *)image
{
// Create image rectangle with current image width/height
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
NSLog(@"convertImageToGrayScale: image.size.width: %f image.size.height: %f", image.size.width, image.size.height);
// Grayscale color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
// Create bitmap content with current image size and grayscale colorspace
CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
// Draw image into current context, with specified rectangle
// using previously defined context (with grayscale colorspace)
CGContextDrawImage(context, imageRect, [image CGImage]);
// Create bitmap image info from pixel data in current context
CGImageRef imageRef = CGBitmapContextCreateImage(context);
// Create a new UIImage object
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
// Release colorspace, context and bitmap information
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
CFRelease(imageRef);
// Return the new grayscale image
return newImage;
}
This is simple enough, given your code:
This works, because, according to the documentation,
-initWithContentsOfFile:will return nil if it couldn’t create the image for any reason (corrupt file, file not found, etc.)