将图像保存为有序索引的二进制数据 [英] save image to binary data of a ordered index

查看:96
本文介绍了将图像保存为有序索引的二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我的快速代码试图将图片图像中的图像追加并将其保存到核心数据中.核心数据属性位于下面的图像中.当用户在文本字段中输入3时,将显示已保存到核心数据中的图像,因为这是索引中的顺序.构建时会保存2张图像,因此新图像应从索引的3开始.

My swift code below is trying to to append the image that is in the pic image and save it into core data. The core data attributes are located in a image below. When the user enters 3 into the textfield the image the saved into core data should appear because that is the order in the index. 2 Images are saved when build so the new image should start at 3 on the index.

import UIKit
 import CoreData
   class ViewController: UIViewController,UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

  var imagePicker: UIImagePickerController!

@IBOutlet var enterT : UITextField!
@IBOutlet var pic : UIImageView!
lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

override func viewDidLoad() {
    super.viewDidLoad()

    enterT.delegate = self

    pic.backgroundColor = .cyan
    populateData()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let text = (textField.text as? NSString)?.replacingCharacters(in: range, with: string), let index = Int(text) else { //here....
        // display an alert about invalid text
        return true
    }
    loadImage(at: index - 1 )
    return true
}




func loadImage(at index : Int) {
    let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
    fetchRequest.predicate = NSPredicate(format: "idx == %d", Int32(index))
    do {
        if let user = try context.fetch(fetchRequest).first {
            pic.image = UIImage(data: user.image!)
        } else {
            pic.image = nil
        }
    } catch {
        print("Could not fetch \(error) ")
    }
}

@IBAction func add(){
      imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    present(imagePicker, animated: true, completion: nil)

}
@IBAction func append(){

}

func populateData()
{
    let item = Users(context: context)
    let vex = UIImage(named: "on.jpg")!.pngData()
    item.image = vex
    item.idx = 0

    let item2 = Users(context: context)
    let vex2 = UIImage(named: "house.jpg")!.pngData()
    item2.image = vex2
    item2.idx = 1

    print("Storing Data..")
    do {
        try context.save()
    } catch {
        print("Storing data Failed", error)
    }
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    // The info dictionary may contain multiple representations of the image. You want to use the original.
    guard let selectedImage = info[.originalImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }

    // Set photoImageView to display the selected image.

    pic.image = selectedImage

    // Dismiss the picker.
    dismiss(animated: true, completion: nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
}
 }

推荐答案

看看方法populateData,这里有创建记录,为属性分配值和保存上下文的代码.

Look at the method populateData, there is the code to create a record, to assign values to the attributes and to save the context.

如果要添加多个图像,则必须计算下一个可用索引.索引通常是已保存项目的数量.如果在索引01处有两个预定义图像,则下一个可用索引是2.

If you want to add multiple images you have to calculate the next available index. The index is usually the number of saved items. If you have two predefined images at index 0 and 1 the next available index is 2.

要动态获取保存的记录数,请创建一个提取请求并在上下文中调用count(for:

To get the number of saved records dynamically create a fetch request and call count(for: on the context

let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
let nextAvailableIndex = try context.count(for: fetchRequest)

这篇关于将图像保存为有序索引的二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆