2012-02-03 10 views
0

「ドキュメント」ディレクトリ内のファイルがpngイメージであるかどうかチェックする機会はありますか?ファイルがイメージでない場合のキャッチエラー

マイアプリがサーバーからPNGファイルをダウンロードします。次に、AppはPNGからグレースケール画像をレンダリングします。サーバー側または通信で何か問題が生じ、pngファイルが破損しているかPNGファイルがない場合、グレースケールレンダリングがアプリケーション全体をクラッシュさせます。

私は今のために行うすべてが経由して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; 
} 
+0

これまでに何を試みましたか?画像の読み込みには何を使用していますか?これらのことは、私たちが皆さんを助けてくれるのを助けてくれるかも –

+0

ありがとうリチャード...詳細を追加しました。 – MadMaxAPP

答えて

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を返しますので、これは、動作します何らかの理由でイメージを作成できなかった場合(破損ファイル、ファイルが見つからないなど)

+0

それは良い解決策です、+1! –

+0

本当にシンプルなソリューションをありがとう! – MadMaxAPP

関連する問題