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

标签 ios image filesystems png

是否有机会检查“文档”目录中的文件是否为 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;
}

最佳答案

这很简单,给定您的代码:

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

关于ios - 如果文件不是图像则捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9130296/

相关文章:

iphone - 调用 setEditing 时自定义 UITableViewCell 调整大小标签

c++ - 如何将文件保存到 C++ 中的所需位置?

ios - 链接两个 segue 看起来像一个

ios - 新的 react-native ios 应用程序没有构建?

objective-c - 如何更改 Apple 示例代码项目 MoviePlayer

java - Java 中的保形变换 - 圆盘到矩形

iPhone:快速读取大量图像

php - 如何避免图片显示在一栏中

c++ - Windows 无缓冲 I/O 和 NCQ

linux - 为什么设备文件的 mtime 没有得到更新?