将图像保存为有序索引的二进制数据 [英] save image to binary data of a ordered index
问题描述
我下面的 swift 代码试图附加 pic 图像中的图像并将其保存到核心数据中.核心数据属性位于下图中.当用户在文本字段中输入 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.
如果要添加多个图像,则必须计算下一个可用索引.索引通常是保存项目的数量.如果您在索引 0
和 1
处有两个预定义的图像,则下一个可用索引是 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屋!