【Xcode5.1.1 + iOS 7.1 + MacOX10.9.4】
前回データ(変数)の保存について書きましたが、今回は画像です。アイコン程度の小さな画像をアプリ内に保存できるようにしたい。
・UIImageJPEGRepresentationを使って、画像をJPEG化。
・[NSHomeDirectory() stringByAppendingPathComponent:@”Documents”]で、データ保存用を一般的に使われるDocumentsディレクトリを指定する。
というところがミソのようです。
で、書いてみたコードがコレ。ここではカメラ/カメラロールを編集モードで呼び出した後に、250*250のjpegに保存する処理を書いています。カメラの呼び出しなどは割愛してます。関数「resize」は、自前の関数であることががわかるように書いておきました。
・YoheiM.NET [XCODE] iPhoneで画像をアプリケーション内に保存するには
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | -( void )imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:( NSDictionary *)info { //編集された画像を取得 UIImage *editedImage = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage]; // 画像をリサイズ UIImage *resize = [ self resize:editedImage rect:CGRectMake(0, 0, 250, 250)]; //リサイズした画像をDocumentsフォルダに保存 NSData *data = UIImageJPEGRepresentation(resize, 1.0f); icon_count++; //画像をアプリ内部に保存 NSString *path = [ NSString stringWithFormat: @"%@/newicon%@.jpg" , [ NSHomeDirectory () stringByAppendingPathComponent: @"Documents" ],[ NSString stringWithFormat: @"%d" ,icon_count]]; //保存に成功・失敗したログをコンソールに出力(デバッグ用) if ([data writeToFile:path atomically: YES ]) { NSLog ( @"Save completed. %@" ,path); //保存した画像のパスを配列に追加 [_array_icon addObject:[ NSString stringWithFormat: @"../Documents/newicon%@.jpg" ,[ NSString stringWithFormat: @"%d" ,icon_count]]]; //アイコン画像配列:保存 if ([_delegate respondsToSelector: @selector (saveData)]){ [_delegate saveData]; } //画像一覧を再描画 [ self .myCollectionView reloadData]; } else { NSLog ( @"could not save" ); } //---ここに保存後の処理を書く。 } //画像をリサイズする - (UIImage *)resize:(UIImage *)image rect:(CGRect)rect { UIGraphicsBeginImageContext(rect.size); [image drawInRect:rect]; UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext(); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetInterpolationQuality(context, kCGInterpolationHigh); UIGraphicsEndImageContext(); return resizedImage; } |
これで前回分と合わせると、保存した画像をアプリ起動時に呼び出せます。
「【Xcode】データをアプリ内に保存するためのメモ2(画像編)」への1件のフィードバック
コメントは停止中です。