UIImagePNGRepresentation always nil for generated QR image [duplicate] - ios

This question already has answers here:
PNG/JPEG representation from CIImage always returns nil
(1 answer)
CIFilter output image nil
(2 answers)
Closed 4 years ago.
I am trying to save a QR code image that was generated in my app, and when doing so I am unable to get the underlying data so that I can save it.
The QR code is generated via CIFilters from a string, nothing special, like so:
if let filter = CIFilter(name: "CIQRCodeGenerator") {
//set the data to the contact data
filter.setValue(contactData, forKey: "inputMessage")
filter.setValue("L", forKey: "inputCorrectionLevel")
if let qrImage = filter.outputImage {
self.qrCode = UIImage(ciImage: codeImage)
}
}
}
And, I'm trying to get the image data to save it to the application documents by doing so:
let data = UIImagePNGRepresentation(self.qrCode)
But, it always returns nil.
I understand the documentation saying that it can return nil if no underlying data is found,
but I am confused at how I can store this image that is generated if there is no underlying data?

Related

Unable to set <UIImage:0x283942880 anonymous {1080, 1080} renderingMode=automatic> to UIImageView XCode Swift

I have built an app which fetches contacts from phonebook and saves their name and photo. To save the photo I've used the following code
if let imageData = contact.thumbnailImageData {
imageStr = String(describing: UIImage(data: imageData)!)
} else {
imageStr = "null"
}
and when I print imageStr using print("IMGSTR: \(imageStr)") I get the following output
IMSTR: <UIImage:0x283942880 anonymous {1080, 1080} renderingMode=automatic>
Now I'm stuck on how to set this string to the UIImageView, I tried
imageview.image = UIImage(named: imageStr)
but it shows nothing
Could someone please help me in how to set the string <UIImage:0x283942880 anonymous {1080, 1080} renderingMode=automatic> to UIImageView?
No need to convert it to a String. UserDefaults supports Data objects. Store it as Data and when setting it to a UIImageView use let image = UIImage(data : imageData)
If you want to convert an instance of Data to String, you should use the String(decoding:as:) initializer, like this.(eg : let str = String(decoding: data, as: UTF8.self)).

How to generate code128 barcode with special character '¿'?

I am developing application with ability to scan barcodes but i have problem with some characters which mess up everything for me. Same problem occured on android and i fixed it but i can't fix it on swift in same fashion.
I have tried multiple libraries and native ways to generate image of code128 barcode from provided String. It works on everything but special characters like '¿'. I tried everything i read after googling problem but i still could not fix it.
extension UIImage {
convenience init?(barcode: String) {
let data = barcode.data(using: .ascii)
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
return nil
}
filter.setValue(data, forKey: "inputMessage")
guard let ciImage = filter.outputImage else {
return nil
}
self.init(ciImage: ciImage)
}
}
let barcode = UIImage(barcode: "some text")
Everything works fine when scanning this exact barcode image from card and saving the value. It even says that ";038388¿" is type code128, but when I try to generate code128 barcode image out of it, somehow it has problem with "¿" character.
Code128 is defined as only capable of encoding ASCII, but ASCII does not have the "¿" character.
The conversion let data = barcode.data(using: .ascii) fails.
I would recommend catching this early using code like
guard let data = barcode.data(using: .ascii) else {
return nil
}

Saving an array of images to parse [duplicate]

This question already has an answer here:
Parse array images saving and fetching
(1 answer)
Closed 5 years ago.
I have an array of images in a UIImage array and I'm looking to save this to parse. I know how to save a regular image to Swift but how do I send multiple images that are all related to each other.
Basically I have a mosaic app that takes an image and beaks it down into 30 smaller images. How can I save those 30 images together to parse with text and other fields as well.
convert image to data
let imageData = UIImagePNGRepresentation(image)
convert data to image
let image = UIImage.init(data: imageData)
Updated
let imagArr = [UIImage.init(named: "a.jpg"),UIImage.init(named: "b.jpg"),UIImage.init(named: "c.jpg")]
let dataArr = NSMutableArray()
for eachImage in imagArr{
dataArr.add(UIImagePNGRepresentation(eachImage!)! as Data)
}
let me know is it helpful or not
compress image if size is big or leave, convert image to to data and data to base64string .. save string to parst ..
on return .. convert base64 string to data and data to image ..
This would be efficient i guess .. i am doing this for iCloud s
synchronization

Saving & retrieving images on Firebase [duplicate]

This question already has answers here:
Swift2 retrieving images from Firebase
(2 answers)
Closed 7 years ago.
On the process of trying Firebase, as a possible replacement to Parse.com (unfortunately to disappear), I have saved a PNG image online using the code below, in Swift.
let fn = self.toolBox.getDocumentsDirectory().stringByAppendingPathComponent("M0-1.png")
let im = UIImage(contentsOfFile: fn),
dat = UIImagePNGRepresentation(im!),
b64 = dat?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
qs = ["string": b64!],
r = diltRootRef.childByAppendingPath("zs"),
us = ["img": qs]
r.setValue(us)
The saving part seems to work, but how am I suppose to get back the image I saved? All I have tried so far failed.
I would recommend retrieving images using observeSingleEventOfType(:_), because it's a one-time read.
Once you have the string value synchronized, you can use an NSData() initializer, and then create an UIImage.
imageRef.observeSingleEventOfType(.Value) { (imageSnap: FDataSnapshot!) in
let base64String = imageSnap.value as! String
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
let image = UIImage(data: decodedData!)
}
Check out this example repo on using base64 images in a UITableView.

Save image with the correct orientation - Swift & Core Image

I'm using Core Image in Swift for editing photos and I have a problem when I save the photo. I'm not saving it with correct orientation.
When I get the picture from the Photo Library I'm saving the orientation in a variable as UIImageOrientation but I don't know how to set it back before saving the edited photo to the Photo Library. Any ideas how?
Saving the orientation:
var orientation: UIImageOrientation = .Up
orientation = gotImage.imageOrientation
Saving the edited photo to the Photo Library:
#IBAction func savePhoto(sender: UIBarButtonItem) {
let originalImageSize = CIImage(image:gotImage)
filter.setValue(originalImageSize, forKey: kCIInputImageKey)
// 1
let imageToSave = filter.outputImage
// 2
let softwareContext = CIContext(options:[kCIContextUseSoftwareRenderer: true])
// 3
let cgimg = softwareContext.createCGImage(imageToSave, fromRect:imageToSave.extent())
// 4
let library = ALAssetsLibrary()
library.writeImageToSavedPhotosAlbum(cgimg,
metadata:imageToSave.properties(),
completionBlock:nil)
}
Instead of using the metadata version of writeImageToSavedPhotosAlbum, you can use :
library.writeImageToSavedPhotosAlbum(
cgimg,
orientation: orientation,
completionBlock:nil)
then you can pass in the orientation directly.
To satisfy Swift, you may need to typecast it first:
var orientation : ALAssetOrientation = ALAssetOrientation(rawValue:
gotImage.imageOrientation.rawValue)!
As per my somewhat inconclusive answer here.
(As you have confirmed, this solution does indeed work in Swift - I derived it, untested, from working Objective-C code)
If you are interested in manipulating other information from image metadata, here are a few related answers I provided to other questions...
Updating UIImage orientation metaData?
Force UIImagePickerController to take photo in portrait orientation/dimensions iOS
How to get author of image in cocoa
Getting a URL from (to) a "picked" image, iOS
And a small test project on github that digs out image metadata from various sources (it's objective-C, but the principles are the same).
You are calling writeImageToSavedPhotosAlbum:metadata:completionBlock:... The docs on that method say:
You must specify the orientation key in the metadata dictionary to preserve the orientation of the image.

Resources