67
67

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CoreDataに画像のサムネイルをバイナリデータで保存する

Last updated at Posted at 2012-02-14

100KB以下のちいさい画像ならCoreDataのモデルにいきなり入れちゃってもOK

  • UIImageをいい感じに四角く切り取って縮小するメソッドをつくる
- (UIImage *)cropImageView:(UIImage *)image
{
    // 切り取る
    float origin_width = image.size.width;
    float origin_heigt = image.size.width;
    CGRect cropRect;
    if (origin_heigt <= origin_width) {
        float x = origin_width / 2 - origin_heigt / 2;
        float y = 0;
        cropRect = CGRectMake(x, y, origin_heigt, origin_heigt);
    } else {
        float x = 0;
        float y = origin_heigt / 2 - origin_width / 2;
        cropRect = CGRectMake(x, y, origin_width, origin_width);
    }
    CGImageRef cgimage = CGImageCreateWithImageInRect(image.CGImage, cropRect);
    UIImage *cropImage = [UIImage imageWithCGImage:cgimage];

    // 縮小する
    CGSize thumbSize = CGSizeMake(80, 80);
    UIGraphicsBeginImageContext(thumbSize);
    [cropImage drawInRect:CGRectMake(0, 0, thumbSize.width, thumbSize.height)];
    UIImage * thumbImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return thumbImage;
}
  • 上記のメソッドからデータを取得して、CoreDataへ保存する
  • thumbは、CoreDataのスキーマ設定でBinary Dataに設定しておくだけでOK
UIImage *thumbImage = [self cropImageView:image];
NSData *dataCropImage = UIImagePNGRepresentation(thumbImage);

Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:self.managedObjectContext];
[photo setValue:dataCropImage forKey:@"thumb"];
  • このサムネイルをDBから取り出して、UITableViewCell上のUIImageViewにセットするには
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSData *data = [managedObject valueForKey:@"thumb"];
UIImage *img = [UIImage imageWithData:data];
cell.photoThumbImageView.image = img;
67
67
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
67
67

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?