Swift Image Name Compare - swift

I am using the below code to work out if the image name in box1Image is equal to "sallywin.png".
Id doesnt seem to work.
How would I go about coding this?
Any help much appreciated
if (box1Image.image?.isEqual(UIImage(named: "smswin.png")))! {
self.box1Image.image = UIImage(named:"sallywin.png")
}

You cannot directly compare two images are same. You can get the images as NSDATA and then you can compare two NSDATA values are equal.

You can compare 2 images using NSData.
let imageName1 : UIImage = UIImage(named: "Selected_1.png")!
let imageName2 : UIImage = UIImage(named: "UnSelected.png")!
let imageView = UIImageView(image: imageName1)
if imageCompare(imageView.image!, isEqualTo: imageName2)
{
print("TRUE")
}
else
{
print("FALSE")
}
func imageCompare(image1: UIImage, isEqualTo image2: UIImage) -> Bool {
let data1: NSData = UIImagePNGRepresentation(image1)!
let data2: NSData = UIImagePNGRepresentation(image2)!
return data1.isEqual(data2)
}

Related

Need help about UIImage to change into a string

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?

how to store [UIImage] into Core Data and retrieve to [UIImage] from binary date

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]

Creating Gif Image Color Maps in iOS 11

I recently was having an issue when creating a Gif where if it got too big colors went missing. However thanks to help from SO someone was able to help me find a work around and create my own color map.
Previous Question here...iOS Colors Incorrect When Saving Animated Gif
This worked great up until iOS 11. I can't find anything in the docs that changed and would make this no longer work. What I have found is if I remove kCGImagePropertyGIFImageColorMap A gif is generated but it has the original issue where colors go missing if the gif gets to large like my previous question. This makes sense as this was added to fix that issue.
Suspected Issue...
func createGifFromImage(_ image: UIImage) -> URL{
let fileProperties: [CFString: CFDictionary] = [kCGImagePropertyGIFDictionary: [
kCGImagePropertyGIFHasGlobalColorMap: false as NSNumber] as CFDictionary]
let documentsDirectoryPath = "file://\(NSTemporaryDirectory())"
if let documentsDirectoryURL = URL(string: documentsDirectoryPath){
let fileURL = documentsDirectoryURL.appendingPathComponent("test.gif")
let destination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, 1, nil)!
CGImageDestinationSetProperties(destination, fileProperties as CFDictionary);
let colorMap = image.getColorMap()
print("ColorMap \(colorMap.exported as NSData)")
let frameProperties: [String: AnyObject] = [
String(kCGImagePropertyGIFImageColorMap): colorMap.exported as NSData
]
let properties: [String: AnyObject] = [
String(kCGImagePropertyGIFDictionary): frameProperties as AnyObject
]
CGImageDestinationAddImage(destination, image.cgImage!, properties as CFDictionary);
if (!CGImageDestinationFinalize(destination)) {
print("failed to finalize image destination")
}
return fileURL
}
//shouldn't get here
return URL(string: "")!
}
Here is a link to download a test project. Note if you run it on a 10.3 simulator it works great but if you run it on iOS 11 it is a white image.
https://www.dropbox.com/s/hdmkwyz47ondd52/gifTest2.zip?dl=0
Other code that is referenced...
extension UIImage{
//MARK: - Pixel
func getColorMap() -> ColorMap {
var colorMap = ColorMap()
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var byteIndex = 0
for _ in 0 ..< Int(size.height){
for _ in 0 ..< Int(size.width){
let color = Color(red: data[byteIndex], green: data[byteIndex + 1], blue: data[byteIndex + 2])
colorMap.colors.insert(color)
byteIndex += 4
}
}
return colorMap
}
}
ColorMap
struct Color : Hashable {
let red: UInt8
let green: UInt8
let blue: UInt8
var hashValue: Int {
return Int(red) + Int(green) + Int(blue)
}
public static func == (lhs: Color, rhs: Color) -> Bool {
return [lhs.red, lhs.green, lhs.blue] == [rhs.red, rhs.green, rhs.blue]
}
}
struct ColorMap {
var colors = Set<Color>()
var exported: Data {
let data = Array(colors)
.map { [$0.red, $0.green, $0.blue] }
.joined()
return Data(bytes: Array(data))
}
}
This is a bug in iOS 11.0 and 11.1. Apple has fixed this in iOS 11.2+
I saw zip project. it's seems not "swifty".. :)
Anyway:
below You can find minimal code that works for iOS 11.
we can start from this
questions:
1) what should happen for different sizes? we muse resize GIF of make a black area around original image in a new big image
2) can you give me more details about color maps?
3) what is all the stuff with matrixes? it seems you want to fill in black? this is not the smart and quicker approach. I will use Apple functions to scale up/fill background.
I can help You once You have kindly answered.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let image = UIImage(named: "image1"){
createGIFFrom(image: image)
}
}
final func localPath()->URL{
let tempPath = NSTemporaryDirectory()
let url = URL.init(fileURLWithPath: tempPath)
return url.appendingPathComponent("test.gif")
}
private final func createGIFFrom(image: UIImage){
let fileURL = self.localPath()
let type: CFString = kUTTypeGIF// kUTTypePNG
// from apple code:
//https://developer.apple.com/library/content/technotes/tn2313/_index.html
guard let myImageDest = CGImageDestinationCreateWithURL(fileURL as CFURL, type, 1, nil) else{
return
}
guard let imageRef = image.cgImage else{
return
}
// Add an image to the image destination
CGImageDestinationAddImage(myImageDest, imageRef, nil)
CGImageDestinationFinalize(myImageDest)
print("open image at: \(fileURL)")
}
}

Uploading multiple Images to Parse

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]

How to get Image Name used in an UIImage?

I am using an UIImage, in which I have an Image, and I want to know the name of image.
That functionality is not built-in to UIImage because images are not always loaded from files. However, you could create a custom UIImageView subclass to fit your needs.
It is not possible. UIImage instance contains the actual image data without any reference to the filename.
Images do not necessarily come from files or other named sources, so not all images even have a name. When you create an image from a file, you could store the name in a separate NSString*, and then refer to that stored name when necessary.
this code will help you out
NSString *imgName = [self.imgView1st image].accessibilityIdentifier;
NSLog(#"%#",imgName);
[self.imgView2nd setImage:[UIImage imageNamed:imgName]];
On later iOS versions it's possible to extract image name from the description. Aware, for the debug use only!
extension UIImage {
/// Extracts image name from a description.
/// * Example description: `<UIImage:0x60000278ce10 named(main: ic_timeline_milestone_bluedot) {16, 16}>`
/// * Example name: `ic_timeline_milestone_bluedot`
/// - warning: For the debug use only.
var name: String? {
let description = self.description
guard let regexp = try? NSRegularExpression(pattern: "\\(main: (.*)\\)", options: []) else { return nil }
guard let match = regexp.matches(in: description, options: [], range: description.fullRange).first else { return nil }
guard match.numberOfRanges > 0 else { return nil }
let idx1 = description.index(description.startIndex, offsetBy: range.lowerBound)
let idx2 = description.index(description.startIndex, offsetBy: range.upperBound)
return String(description[idx1..<idx2])
}
}
This answer (https://stackoverflow.com/a/72542728/897465) has (what I believe) the best answer:
let img = UIImage(named: "something")
img?.imageAsset?.value(forKey: "assetName")
Here's a handy extension for it:
extension UIImage {
var containingBundle: Bundle? {
imageAsset?.value(forKey: "containingBundle") as? Bundle
}
var assetName: String? {
imageAsset?.value(forKey: "assetName") as? String
}
}