My swifts code goal is to fetch the last image from binary data pic and display it in imageview picture. Right now its cusing a runtime error with indexpath. I did a similar thing with a string and it worked. The problem is converting binary data to a uiimage.
var picture = UIImageView()
var itemName : [NSManagedObject] = []
var itemNamez : [Info] = []
func loadImage(){
if let imageData = itemNamez[IndexPath.last] {
let coredataLoadedimage = UIImage(data: imageData)
picture.image = coredataLoadedimage
}
}
Related
Need help...
private func classifyImage() {
let currentImageName = classifyimage
guard let image = UIImage(named: currentImageName?.convertToBuffer() as! String),
let resizedImage = image.resizeImageTo(size:CGSize(width: 224, height: 224)),
let buffer = resizedImage.convertToBuffer()
else {
return
}
let output = try? model.prediction(image: buffer)
}
Originally the codes should be produced as arrays but I'm trying to put image input without arrays and recognize the images. It keep saying it has to be a string and I have placed an unwrapped but still it doesn't work... Any idea what to do?
my code is like these:
//save to core data
func addPaper(){
let paper = Paper(context: self.context)
paper.id = UUID()
paper.subject = self.subject
paper.score = Float(self.score) ?? 0
paper.title = self.title
let imgs = try? NSKeyedArchiver.archivedData(withRootObject: self.images, requiringSecureCoding: true)
paper.images = imgs
try? self.context.save()
}
//retrieve to [UIImage]
let imgs = NSKeyedUnarchiver.unarchivedObject(ofClass: [UIImage], from: paper.images!)
there is an error tip:Static method 'unarchivedObject(ofClass:from:)' requires that '[UIImage]' conform to 'NSCoding'
I don't know what to do next, can anyone give me some help?
You should not store image in CoreData. Maybe store in base64 format, and you can encode/decode whenever you want.
Base64 To image:
func base64ToImage(data: String) -> Data{
let encodedImageData = data
let imageData = Data(base64Encoded: encodedImageData)
return imageData!
}
imageView.image = UIImage(data: dataDecoded)
Image to base64
func imageToBase64(image: UIImage) -> String {
return image.pngData()!
.base64EncodedString()
}
maybe you need this, any object can be saved to core data.
:https://stackoverflow.com/questions/56453857/how-to-save-existing-objects-to-core-data
I copied the following steps from others, hope it helps
1.making your custom types (Exercise) subclass of NSObject
2.setting the attribute's type in the core data model to Transformable
3.setting the CustomClass to [Exercise]
I'm building a simple app which you click on a button and the image change randomly but I also want to add a label which describes the image so I created a dictionary contains the ["fileName":"Description"] but when I try changing the image I get an error:
"Cannot subscript a value of type '[String : String]' with an index of type 'Int'"
var randomNumber = 0
let arrayOfImages : [String:String] = ["ball1":"yes","ball2":"no","ball3":"ask again later","ball4":"the answer is yes","ball5":"i dont know"]
func rollButton() {
randomNumber = Int.random(in: 0...4)
ballImage.image = UIImage(named: arrayOfImages[randomNumber])
}
How can I change the UIImage.image using a Dictionary?
Replace
ballImage.image = UIImage(named: arrayOfImages[randomNumber])
with
ballImage.image = UIImage(named: Array(arrayOfImages.keys)[randomNumber])
As you can't subscript a dictionary it's for arrays , A good practice is to create
struct Item {
let imageName:String
let des:String
}
let arr = [Item(imageName: "ball1", des: "con1"),Item(imageName: "ball2", des: "con2"),Item(imageName: "ball3", des: "con3")]
let ran = arr[Int.random(in: 0...2)]
ballImage.image = ran.imageName
You are creating a list of [String: String], so you should access it using a key (String) and not a number (Int).
So you should correct this:
ballImage.image = UIImage(named: arrayOfImages["ball\(randomNumber)"])
I am wondering if its possible to upload 10 images to parse, and then be able to display them in TableView displaying the users username.
So basically when I download them from parse I'm guessing there needs to be something linking those images to the same user or that 1 individual post...
Not sure if this is possible, but I read these two questions and I think you can!
How do I store multiple pictures to a single column in Parse?
Storing images from [UIImage] array to Parse
If anyone understands what I mean, I would love your help!
Best regards.
As discussed, you can add the array of images to a column in your User class, the code below allows you to create a new user and will take an image array and create as many columns as necessary. They will be titled "imageArray0", "imageArray1" and so on. The next time you create a user with images they will automatically be added to the corresponding columns in Parse.
UPDATE
Added image conversion:
let user = PFUser()
user.username = chosenUsername
for i in imageArray.indices {
let imageData = imageArray[i].mediumQualityJPEGNSData
let imageFile = PFFile(name: "image.JPEG", data: imageData)
user["imageArray\(i)"] = imageFile
}
user.signUpInBackgroundWithBlock({
success, error in
if error == nil {
} else {
}
})
I also use this extension to easily convert images to various qualities:
extension UIImage {
var uncompressedPNGData: NSData { return UIImagePNGRepresentation(self)! }
var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)! }
var highQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.75)! }
var mediumQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.5)! }
var lowQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 0.25)! }
var lowestQualityJPEGNSData:NSData { return
UIImageJPEGRepresentation(self, 0.0)! }
}
I'm not sure that is possible but is unnecessary for two reasons:
Speed of query when you want to retrieve the images array
You can save each image under the same row but separately under the Image x number
and finally you can't save a UIImage Array it will have to be a NSData Array so convert the UIImages into NSData's using
let image1 : NSData = UIImagePNGRepresentation([UIImage][0]!)!
let image2 : NSData = UIImagePNGRepresentation([UIImage][1]!)!
let image3 : NSData = UIImagePNGRepresentation([UIImage][2]!)!
let imageArray : [NSData] = [image1, image2, image3]
I'm new at this so sorry if this is basic but I'm trying to use an array in a json file and have it point to an image in my asset library but I'm running into problems. Its written as:
[
{
"image":"shrew",
},
]
Is it wrong to write it as a string? Do I need to have specific code to translate the string into my image names?
Thanks for any help you can offer!
Edit:
The error I'm getting is on line
TrackPic.image = image
"Use of unresolved identifier 'TrackPic'"
class QuizModel: NSObject {
func getQuestions() -> [Question] {
// Array of question objects
var questions:[Question] = [Question]()
// Get Json array of dictionaries
let jsonObjects:[NSDictionary] = self.getLocalJsonFile()
// Loop through each dictionary and assign values to our question objs
var index:Int
for index = 0; index < jsonObjects.count; index++ {
// Current JSON dict
let jsonDictionary:NSDictionary = jsonObjects[index]
// Create a question obj
var q:Question = Question()
let imageName = jsonDictionary["image"] as! String
let image = UIImage(named: imageName)
TrackPic.image = image
// Assign the values of each key value pair to the question object
q.image = jsonDictionary["image"] as! String
q.questionText = jsonDictionary["question"] as! String
q.answers = jsonDictionary["answers"] as! [String]
q.correctAnswerIndex = jsonDictionary["correctIndex"] as! Int
q.module = jsonDictionary["module"] as! Int
q.lesson = jsonDictionary["lesson"] as! Int
q.feedback = jsonDictionary["feedback"] as! String
// Add the question to the question array
questions.append(q)
}
// Return list of question objects
return questions
}
you first need to get the image name from the json like you did
let imageName = jsonDictionary["image"] as! String
(If you want to be certain that you are parsing your JSON correctly, be sure to write the imageName to the console)
Then you need to initialise a UIImage with UIImage(named: String) with you image name from json so
let image = UIImage(named : imageName)
Then you have your image, and you can put this on an UIImageView.
I suppose in your case, this would be
q.image = image
IF q is a UIImageView