-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];//
UIImage *cmpImg = [appDelegate scaleImage:image toScale:kImageScaleRate];//縮圖
NSData *blobImage = UIImageJPEGRepresentation(cmpImg, kImageCompressRate);//圖片壓縮為NSData
[self dismissModalViewControllerAnimated:YES];
[self updateImage:blobImage withIndexPath:indexPath_];//更新圖片(自定義函數)
}
叫起圖片選取器-(void)snapImage:(id)sender
{
UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//圖片來源
ipc.videoQuality = UIImagePickerControllerQualityTypeLow;
ipc.delegate = self;
ipc.allowsEditing = NO;
[self presentModalViewController:ipc animated:YES];
}
縮圖函數(自定義)- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
[image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
儲存至資料庫※圖片傳入時已是NSData-(void)updateImage:(NSData*)image withIndexPath:(NSIndexPath*)indexPath{
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSDate* spentDate = [(SpentMoney*)[dailyContent objectAtIndex:indexPath.row] spentDate];
NSString *date = [NSString stringWithString:[dateformat stringFromDate: spentDate]];
//圖片傳入的時候,已經是NSData了,所以只要單純寫入即可
BOOL sucess = [fmdb executeUpdate:@"update spentMoney set contentImage =? where spentDate=?",image, date];
if (!sucess) {
[appDelegate showMessageWith:@"fail to insert image" andMessage:nil];
}
dateformat = nil;
[self fetchData];
}
自資料庫讀取,範例是tableView的Cell資料呈現的內容,看紅色字部份- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
SpentMoney *spentMoney = [dailyContent objectAtIndex:indexPath.row];
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
dateformat.dateFormat = @"HH:mm:ss";
cell.textLabel.text = [dateformat stringFromDate: spentMoney.spentDate];
cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@",spentMoney.money];
//圖片存至資料庫時是用NSData,讀取也只要用imageWithData把圖片讀取出來
cell.imageView.image = [UIImage imageWithData:spentMoney.contentImage];
return cell;
dateformat = nil;
}
联系客服