如果文件不是图像,则捕获错误

时间:2012-02-03 14:35:06

标签: ios image filesystems png

是否有可能检查“documents”目录中的文件是否为png图像?

我的应用程序从服务器下载一些PNG文件。然后,应用程序从PNG渲染灰度图像。如果在服务器端或通信中出现问题,并且png文件已损坏或没有PNG文件,则灰度渲染会使我的整个应用程序崩溃。

我现在所做的就是通过以下方式将Documents目录中的文件加载到UIImage对象中:

UIImage *myImage = [[UIImage alloc] initWithContentsOfFile:[myobject.localFolder stringByAppendingPathComponent:@"thumbnail.png"]]

然后我调用该方法将图像转换为灰度,使用此UIImage。 这是我用来渲染灰度图像的函数:

- (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;
}

1 个答案:

答案 0 :(得分:4)

这很简单,给出你的代码:

UIImage *myImage = [[UIImage alloc] initWithContentsOfFile:[myobject.localFolder stringByAppendingPathComponent:@"thumbnail.png"]];

if (myImage)
{
    UIImage *grayImage = [self convertToGrayscale:myImage];
}
else
{
    // notify the user that the file is corrupt.
}

这是有效的,因为根据documentation-initWithContentsOfFile:如果由于任何原因无法创建图像(腐败文件,找不到文件等)将返回nil