gpt4 book ai didi

core-data - SwiftUI ImagePicker 将 (Image -> UIImage --> Data) 保存到 Core Data

转载 作者:行者123 更新时间:2023-12-05 02:06:17 32 4
gpt4 key购买 nike

大家好我有点沮丧,所以我希望得到一些帮助。我的项目在 SwiftUI 中。我想使用图像选择器将图像保存到 Core Data。我实现了让 ImagePicker 工作,但我正在努力转换 Image --> UIImage --> Data 以保存它。项目运行无误,但不保存图像。要知道问题出在哪里,我执行了 3 个打印语句。 image=给一个值,UIImage(inputImage)=nil,Data当然是nil。

import SwiftUI


struct AddNewBean: View {

@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Bean.entity(), sortDescriptors: []) var beans: FetchedResults<Bean>
@State var BeanRoaster: String = ""
@State var BeanName: String = ""
@State var BeanStyle: String = "Dark"

@State private var RoastDate = Date()
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter }

@State private var showImagePicker : Bool = false
@State private var image : Image?
@State private var inputImage: UIImage?
@State var imageAlt: Data = .init(count: 0)

let RStyles = ["Dark", "Medium", "Light"]

func loadImage() {
guard let inputImage = inputImage else { return }
image = Image(uiImage: inputImage)
}

var body: some View {

NavigationView {
VStack {
Form {
VStack {
image?.resizable().scaledToFit().aspectRatio(contentMode: .fit)
HStack {
Spacer()
Button("Open Camera"){
self.showImagePicker = true
}.padding(5)
.foregroundColor(Color.white)
.background(Color.accentColor)
.cornerRadius(10)
Spacer()
}.sheet(isPresented: self.$showImagePicker, onDismiss: loadImage){
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
}
}
TextField("Röster", text: $BeanRoaster)
TextField("Name der Bohne", text: $BeanName)
Picker("Roestung", selection: $BeanStyle) {
ForEach(RStyles, id: \.self) {
Text($0)
}
}
DatePicker(selection: $RoastDate, in: ...Date(), displayedComponents: .date) {Text("Röstdatum")}

HStack {
Spacer()
if BeanRoaster != "" && BeanName != "" {
Button(action: {
//....
let pickedImage = self.inputImage?.jpegData(compressionQuality: 1.0)
print("image, inputimage, pickedImage")
print(self.image as Any) // prints: Optional(SwiftUI.Image(provider: SwiftUI.ImageProviderBox<__C.UIImage>))
print(self.inputImage as Any) // prints: nil
print(pickedImage as Any) // prints: nil
//.....
let bean = Bean(context: self.moc)
bean.id = UUID()
bean.roaster = "\(self.BeanRoaster)"
bean.name = "\(self.BeanName)"
bean.roastStyle = "\(self.BeanStyle)"
bean.roastDate = self.RoastDate
bean.active = true
bean.img = pickedImage

try? self.moc.save()
self.presentationMode.wrappedValue.dismiss()
}) {
Image(systemName: "tray")
.foregroundColor(.blue)
.font(.largeTitle)
.padding(.vertical)
}
Text("Save").foregroundColor(.blue)
Spacer()
} else {
HStack {
Spacer()
Text("Trage Bohnendaten ein!")
Spacer()
}
}
}

Section {
HStack {
Spacer()
Button(action: {self.presentationMode.wrappedValue.dismiss()}) {
Image(systemName: "")
.foregroundColor(.red)
.font(.largeTitle)
.padding(.vertical)
}
Text("Dismiss").foregroundColor(.red)
Spacer()
}
}
}.navigationBarTitle("New Bean")
}
}
}
}

最佳答案

下面是我现有应用程序中的几行代码,我对其进行了简化。我的方法是简单地从 Image Picker 取回图像数据,而不是 UIImage。这对我很有效。

ContentView

struct ContentView: View {
@Environment(\.managedObjectContext) var viewContext

@FetchRequest(entity: Images.entity(), sortDescriptors: [], animation: Animation.easeInOut)
var images: FetchedResults<Images>

@State private var showImagePicker = false
@State private var image = Image(systemName: "person.circle.fill")
@State private var data: Data?
@State private var optionalData = UIImage(systemName: "person.circle.fill")?.jpegData(compressionQuality: 1)

var body: some View {
VStack {
ForEach(images) { image in
Image(uiImage: UIImage(data: (image.imageData ?? optionalData)!)!)
// your modifiers
}

image
.resizable()
.frame(width: 150, height: 150)

Button(action: {
showImagePicker = true
}) {
Text("Select")
}

Button(action: {
let newImage = Images(context: viewContext)
newImage.imageData = data

do {
try viewContext.save()
print("Image Saved!")
} catch {
print(error.localizedDescription)
}
}) {
Text("Save")
}
}
.sheet(isPresented: $showImagePicker, onDismiss: loadImage) {
ImagePicker(data: $data)
}
}

func loadImage() {
guard let data = data else { return }

image = Image(uiImage: UIImage(data: data) ?? UIImage(systemName: "person.circle.fill")!)
}
}

ImagePicker

struct ImagePicker: UIViewControllerRepresentable {
@Environment(\.presentationMode) var presentationMode
@Binding var data: Data?

class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker

init(_ parent: ImagePicker) {
self.parent = parent
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.data = uiImage.jpegData(compressionQuality: 1)
}
parent.presentationMode.wrappedValue.dismiss()
}
}

func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.sourceType = .photoLibrary
picker.delegate = context.coordinator

return picker
}

func makeCoordinator() -> Coordinator { Coordinator(self) }

func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { }
}

关于core-data - SwiftUI ImagePicker 将 (Image -> UIImage --> Data) 保存到 Core Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62831253/

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