1

所以我有 2 个视图,其中一个是 UITableVew,用户可以通过添加它们来填充单元格。第二个视图是他们添加时的信息(姓名、日期、公司和扫描条形码的位置。)。好吧,当他们扫描该图像时,他们可以看到他们扫描的图像(使用 Zbar 条形码扫描仪完成)。所以主要问题是如何在用户添加的每个不同单元格中准确保存不同的图像?

代码:

兹巴:

    - (IBAction)cameraButtonTapped:(id)sender
    {
    // Check for camera
    if ([UIImagePickerController               isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == YES) {
        // Create image picker controller
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

        // Set source to the camera
        imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;

        // Delegate is self
        imagePicker.delegate = self;

        // Show image picker
        [self presentModalViewController:imagePicker animated:YES];
    }

    }


    - (void) imagePickerController: (UIImagePickerController*)reader
    didFinishPickingMediaWithInfo: (NSDictionary*) info
    {
    // ADD: get the decode results
    id<NSFastEnumeration> results =
    [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    for(symbol in results)
        // EXAMPLE: just grab the first barcode
        break;

    // EXAMPLE: do something useful with the barcode data
    resultText.text = symbol.data;

    // EXAMPLE: do something useful with the barcode image
    resultImage.image =
    [info objectForKey: UIImagePickerControllerOriginalImage];

    // ADD: dismiss the controller (NB dismiss from the *reader*!)

    [reader dismissModalViewControllerAnimated:YES];

    }

    -(UIView*)CommomOverlay{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];

    UIImageView *TopBar = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,58)];
    [TopBar setImage:[UIImage imageNamed:@""]];
    [view addSubview:TopBar];

    UILabel *Toplabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 9, 300, 30)];
    [Toplabel setFont:[UIFont fontWithName:@"Heiti TC light" size:22]];
    [Toplabel setTextAlignment:UITextAlignmentCenter];
    [Toplabel setBackgroundColor:[UIColor clearColor]];
    [Toplabel setTextColor:[UIColor lightGrayColor]];
    [Toplabel setNumberOfLines:1];
    [Toplabel setText:@"Turn your device sideways to scan"];
    [TopBar addSubview:Toplabel];

    UIImageView *FrameImg = [[UIImageView alloc] initWithFrame:CGRectMake(40,50,240,370)];
    [FrameImg setImage:[UIImage imageNamed:@"scanImage.png"]];
    [view addSubview:FrameImg];
    return view;
}



- (IBAction) scanButtonTapped
{
    // ADD: present a barcode reader that scans from the camera feed
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
    reader.supportedOrientationsMask = ZBarOrientationMaskAll;

    ZBarImageScanner *scanner = reader.scanner;
    // TODO: (optional) additional reader configuration here

    // EXAMPLE: disable rarely used I2/5 to improve performance
    [scanner setSymbology: ZBAR_I25
                   config: ZBAR_CFG_ENABLE
                       to: 0];

    // present and release the controller
    reader.cameraOverlayView = [self CommomOverlay];

    [self presentModalViewController: reader
                            animated: YES];

}

我确实考虑过使用核心数据,但我在任何地方都找不到教程。然后我想将它保存在应用程序文档文件夹中,我认为这对我来说是最好的方式。我是新手,所以描述性代码会有所帮助:)

更新:

- (IBAction)save:(id)sender {
    NSManagedObjectContext *context = [self managedObjectContext];

    UIImage *image = resultImage.image;
    NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
    NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
    NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@KYRO Receipts Images/Barcode.png", resultImage]]; //add our image to the path
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
    NSLog(@"image saved");

    if (self.device) {
        // Update existing device
        [self.device setValue:self.nameOfItem.text forKey:@"name"];
        [self.device setValue:self.dateOfPurchase.text forKey:@"date"];
        [self.device setValue:self.companyOfItem.text forKey:@"company"];


    } else {
       // 
        NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Receipt" inManagedObjectContext:context];
        [newDevice setValue:self.nameOfItem.text forKey:@"name"];
        [newDevice setValue:self.dateOfPurchase.text forKey:@"date"];
        [newDevice setValue:self.companyOfItem.text forKey:@"company"];

    }

    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    [WTStatusBar setStatusText:@"Saving data..." animated:YES];
    [self performSelector:@selector(setTextStatusProgress3) withObject:nil afterDelay:0.1];

        [self.navigationController popViewControllerAnimated:YES];
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];


}
4

1 回答 1

1

如果您已经在使用 Core Data,那么根据图像的大小,您可以将它们转换为 NSData 并将它们直接保存在 Core Data 中(如果它们很小),或者您可以将它们保存在文档目录中并保存Core Data 中的文件名。

由于完整的 Core Data 教程超出了这里的范围,我只会以唯一的名称将图像保存到文档目录中。请注意,下面的一些代码改编自“ iOS 编程:大书呆子牧场指南”。

// Method to save your image file. Returns the file name for you to save in Core Data or elsewhere.
- (NSString *)saveImage:(UIImage *)image {
    // Generate a unique key to name the image file
    CFUUIDRef newUniqueID = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef newUniqueIDString = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID);
    NSString *imgkey = (__bridge NSString *)newUniqueIDString;

    // Get a path for the image file in the documents directory
    NSString *imagePath = [self imagePathForKey:imgkey];

    // Convert the UIImage into NSData and save it to the documents directory
    NSData *imageData = UIImageJPEGRepresentation(img, 0.5);
    [imageData writeToFile:imagePath atomically:YES];

    // Clean up
    CFRelease(newUniqueIDString);
    CFRelease(newUniqueID);

    return imgkey;
}

// Method to provide the image path for saving/retrieving the image
- (NSString *)imagePathForKey:(NSString *)key {
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [documentDirectories objectAtIndex:0];

    return [documentDirectory stringByAppendingPathComponent:key];
}

以下方法检索图像:

- (UIImage *)imageForKey:(NSString *)imgkey {
    result = [UIImage imageWithContentsOfFile:[self imagePathForKey:imgkey thumbnail:FALSE]];
    if (!result) {
        // File not found - add code here as needed (to return default image or whatever)
    }
    return result;
}

请注意,如果您计划同时在表格中显示多个图像,则必须小心确保它们很小,否则您可能会遇到内存问题。在这种情况下,您可能希望将它们转换为表格视图的缩略图形式,然后仅在详细视图中显示全尺寸图像(如何生成缩略图将是一个单独的问题)。

于 2013-03-25T12:28:00.863 回答