Swift 3 base64 encode image for upload - uiimage

I have some nice code that allows me to pic and image and then display it in app. I was also uploading the profilePic.image to my database (as a blob) but I realised that this was not actually uploading the image itself but just data about the image so I could not render anything back as there was nothing to decode. So I want to transform this function to get the chosen image and encode it to base64 and utilise same working upload
func imagePickerController(
_ selectImage: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject])
{
let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage //2
// imageByCroppingToRect()
profilePic.contentMode = .scaleAspectFit //3
profilePic.image = chosenImage //4
dismiss(animated: true, completion: nil) //5
}

You have to convert the UIImage to a format your website can read, e.g. jpeg before encoding it in base 64.
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(chosenImage, jpegCompressionQuality)?.base64EncodedString() {
// Upload base64String to your database
}
Note: In iOS 12 UIImageJPEGRepresentation was replaced by an instance method jpegData of UIImage:
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = chosenImage.jpegData(compressionQuality: jpegCompressionQuality)?.base64EncodedString() {
// Upload base64String to your database
}
Refer to the Apple documentation for UIImageJPEGRepresentation and Data

Data has a function to return a base64 representation of itself as another Data. No need to convert to String and back.
Take a look at the docs for Data.base64EncodedData()
if let data = UIImageJPEGRepresentation(photos, 0.5)?.base64EncodedData() {
form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
}

Related

Load an image from a Base64-encoded string [duplicate]

This question already has answers here:
Decode Base-64 encoded PNG in an NSString
(6 answers)
Closed 5 years ago.
So I have an empty image view inside a .xib file. And there is another .m file that is a string but there an image loaded inside of it. Can someone please explain in detail how to load the image from the string and put it inside the imageview thats in the xib file?
If it's base64 string, you could use this type of website to extract it : http://codebeautify.org/base64-to-image-converter
In swift you could use this code to get the Image:
let dataFromBase64 = NSData(base64EncodedString: yourString, options: NSDataBase64DecodingOptions(rawValue: 0))!
let image = UIImage(data: dataFromBase64)!
yourImageView.image = image
Hope it helps.
Pierre
For Swift 3.
extension String {
public func base64ToImage() -> UIImage? {
if let dataDecoded = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters) {
return UIImage(data: dataDecoded)
}
return nil
}
}
Them you call:
if let image = yourBase64Image.base64ToImage() {
imageView.image = image
}
Hope it helps.

Xcode - how to display image from url

I am able to display image from the sources, but was wondering how to display image from the URL link:
ccell.avatarImageView.image= [UIImage imageNamed:#"home_new.png"];
Thanks for the help.
Add this outside of the class scope:
import UIKit
extension UIImageView {
func loadurl(url: URL) {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
}
Then add this to wherever you're trying to load your image:
let urlYourURL = URL (string: #"home_new.png")
avatarImageView.loadurl(url: urlYourURL!)
Download the image as data from URL using NSURLConnection and use below code
let imageView:UIImageView = UIImageView.init(image: UIImage.init(data: **data**, scale: 1.0));

How to save and load file image by swift

I have UIImage (got from Parse - convert variable PFFile).
How can I save and load image from this variable?
let a = object["image"] as! PFFile
a.getDataInBackgroundWithBlock({ (data:NSData?, error:NSError?) -> Void in
if (error == nil) {
// I have image, but the next I don't know what I do
let image = UIImage(data:data!)
}
})
Save image png
func saveImage(image:UIImage,name:String){
let selectedImage: UIImage = image
let data:NSData = UIImagePNGRepresentation(selectedImage)
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let success = fileManager.createFileAtPath(path, contents: data, attributes: nil)
print(success)
// Check image saved successfully
let getImagePath = (path as NSString).stringByAppendingPathComponent(name)
if fileManager.fileExistsAtPath(getImagePath) {
// image save success
let image = UIImage(contentsOfFile: getImagePath)!
}
else{
// image save error
}
}
Save other file
static func saveFile(fileData:NSData,name:String)->Bool{
let success = NSFileManager.defaultManager().createFileAtPath(path+"/"+name, contents: fileData, attributes: nil)
return success
}

Swift2 retrieving images from Firebase

I am trying to read/display an image from Firebase. I am first encoding the image and then posting this encoded String to Firebase. This runs fine. When I try and decode the encoded string from Firebase and convert it to an image, I am getting a nil value exception.
This is how I am saving the image to Firebase
var base64String: NSString!
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
imageToPost.image = image
var uploadImage = image as! UIImage
var imageData = UIImagePNGRepresentation(uploadImage)!
self.base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let ref = Firebase(url: "https://XXX.firebaseio.com")
var quoteString = ["string": self.base64String]
var usersRef = ref.childByAppendingPath("goalImages")
var users = ["image": quoteString]
usersRef.setValue(users)
displayAlert("Image Posted", message: "Your image has been successfully posted!")
}
This is how I am trying to read the image from Firebase
// ViewController.swift
import UIKit
import Firebase
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
var base64String: NSString!
#IBAction func buttonClicked(sender: AnyObject) {
sender.setTitle("\(sender.tag)", forState: UIControlState.Normal)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let ref = Firebase(url: "https://XXX.firebaseio.com/goalImages/image/string")
ref.observeEventType(.Value, withBlock: { snapshot in
self.base64String = snapshot.value as! NSString
let decodedData = NSData(base64EncodedString: self.base64String as String, options: NSDataBase64DecodingOptions())
//Next line is giving the error
var decodedImage = UIImage(data: decodedData!)
self.image.image = decodedImage
}, withCancelBlock: { error in
print(error.description)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The error says: "fatal error: unexpectedly found nil while unwrapping an Optional value"; decodedData is nil. Could someone explain what is going wrong.
Instead of
let decodedData = NSData(base64EncodedString: self.base64String as String,
options: NSDataBase64DecodingOptions())
try adding IgnoreUnknownCharacters
NSDataBase64DecodingOptions.IgnoreUnknownCharacters
Use Example: Encode a jpg, store and read from firebase
encode and write our favorite starship
if let image = NSImage(named:"Enterprise.jpeg") {
let imageData = image.TIFFRepresentation
let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let imageRef = myRootRef.childByAppendingPath("image_path")
imageRef.setValue(base64String)
read and decode
imageRef.observeEventType(.Value, withBlock: { snapshot in
let base64EncodedString = snapshot.value
let imageData = NSData(base64EncodedString: base64EncodedString as! String,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = NSImage(data:imageData!)
self.myImageView.image = decodedImage
}, withCancelBlock: { error in
print(error.description)
})
EDIT 2019_05_17
Update to Swift 5 and Firebase 6
func writeImage() {
if let image = NSImage(named:"Enterprise.jpg") {
let imageData = image.tiffRepresentation
if let base64String = imageData?.base64EncodedString() {
let imageRef = self.ref.child("image_path")
imageRef.setValue(base64String)
}
}
}
func readImage() {
let imageRef = self.ref.child("image_path")
imageRef.observeSingleEvent(of: .value, with: { snapshot in
let base64EncodedString = snapshot.value as! String
let imageData = Data(base64Encoded: base64EncodedString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
let decodedImage = NSImage(data: imageData)
self.myImageView.image = decodedImage
})
}
Firebase Engineer here:
I highly recommend using the new Firebase Storage API for uploading images to Firebase. It's simple to use, low cost, and backed by Google Cloud Storage for huge scale.
You can upload from NSData or an NSURL pointing to a local file (I'll show NSData, but the principle is the same):
// Data in memory
let data: NSData = ...
// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")
// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putData(data, metadata: nil) { metadata, error in
if (error != nil) {
// Uh-oh, an error occurred!
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL
// This can be stored in the Firebase Realtime Database
// It can also be used by image loading libraries like SDWebImage
}
}
You can even pause and resume uploads, and you can easily monitor uploads for progress:
// Upload data
let uploadTask = storageRef.putData(...)
// Add a progress observer to an upload task
uploadTask.observeStatus(.Progress) { snapshot in
// Upload reported progress
if let progress = snapshot.progress {
let percentComplete = 100.0 * Double(progress.completedUnitCount) / Double(progress.totalUnitCount)
}
}

Paste gif image into NSPasteboard

I am developing osx application. I want to paste an Gif image into pasteboard. How can I do that?
What I have is
NSImage
NSPasteboard
What I want to do is to paste that image into pasteboard. I am able to paste PNG image but what I need is to paste GIF image.
My existing code
let imageURL = imageObject.imageURL!
let fileName = imageURL.lastPathComponent
var saveURL = NSURL(string: "file://" + NSTemporaryDirectory())
saveURL = saveURL?.URLByAppendingPathComponent(fileName!)
// I have data now
let data = NSData(contentsOfURL: imageURL)
pasteboard.declareTypes([NSTIFFPboardType], owner: nil)
pasteboard.setData(data!, forType: "com.compuserve.gif")
About 10 years ago same one asked How do I put a GIF onto an NSPasteboard?
in an Apple discussion group and here is my answer. Although 10 years old and the NSPasteboard methods changed since that time my answer still works. I confess: my advice is a bit dirty.
Okay I got it working after spending 6 hours searching online.
Basically I have to download the image file and paste it as a filename.
let imageURL = imageObject.imageURL!
let fileName = imageURL.lastPathComponent
var saveURL = NSURL(string: "file://" + NSTemporaryDirectory())
saveURL = saveURL?.URLByAppendingPathComponent(fileName!)
let data = NSData(contentsOfURL: imageURL)
data?.writeToURL(saveURL!, atomically: true)
pasteboard.declareTypes([NSFilenamesPboardType], owner: nil)
pasteboard.writeObjects([saveURL!])
I managed to get this working using the following code:
let pb = NSPasteboard.general
do {
let fileType = try NSWorkspace.shared.type(ofFile: localPath.path)
let pasteboardType = NSPasteboard.PasteboardType.init(fileType)
pb.declareTypes([pasteboardType], owner: nil)
pb.writeObjects([localPath as NSURL])
} catch {
return
}

Resources