gpt4 book ai didi

swift - 将图像保存为有序索引的二进制数据

转载 作者:行者123 更新时间:2023-11-30 10:25:23 26 4
gpt4 key购买 nike

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

enter image description here

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,其中包含创建记录、为属性赋值以及保存上下文的代码。

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

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

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

关于swift - 将图像保存为有序索引的二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60086549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com