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

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.

Related

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));

Swift 3 base64 encode image for upload

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")
}

Converting an Image to Data and Vice Versa [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am using swift in Xcode and I need to convert an image to data in order to save it in SQLite db and also to convert the data object back to an image when I retrieve it from the database.
Any help please?
Simon
Swift 5.1 or later
To convert from UIImage to Data you can use UIImagePNGRepresentation or UIImageJPEGRepresentation if you need to reduce the file size.
extension UIImage {
var jpeg: Data? { jpegData(compressionQuality: 1) } // QUALITY min = 0 / max = 1
var png: Data? { pngData() }
}
To convert back to Image from Data you just need to use UIImage(data:) initializer:
extension Data {
var uiImage: UIImage? { UIImage(data: self) }
}
Playground
let image = UIImage(data: try! Data(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!))!
if let jpegData = image.jpeg {
print(jpegData.count) // 416318 number of bytes contained by the data object
if let imageFromData = jpegData.image {
print(imageFromData.size) // (719.0, 808.0)
}
}
if let pngData = image.png {
print(pngData.count) // 1282319
if let imageFromData = pngData.image {
print(imageFromData.size) // (719.0, 808.0)
}
}

Swift 2.0 - stringByAppendingPathComponent error conversion [duplicate]

This question already has answers here:
stringByAppendingPathComponent is unavailable
(11 answers)
Closed 7 years ago.
I have updated Xcode to 7 all my apps, after the conversion from swift to swift 2.0, got errors that after a bit of research I was able to manually fix them.
However, I have an error with 'stringByAppendingPathComponent' that I cannot solve. It seems that swift 2.0 removed this method.
The picture attached shows the error I am tiling about.
Any Idea how to solve this issue?
func loadNotes(){
let plistPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let DocumentsDirectory = plistPath[0] as! String
let path = DocumentsDirectory.stringByAppendingPathComponent("notes.plist")
let fileManager = NSFileManager.defaultManager()
if (!fileManager.fileExistsAtPath(path)) {
if let bundlePath = NSBundle.mainBundle().pathForResource("notes", ofType: "plist") {
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
println("Bundle notes.plist file is --> \(resultDictionary?.description)")
fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
println("copy")
} else {
println("notes.plist not found")
}
}else {
println("note.plist already exists")
//fileManager.removeItemAtPath(path, error: nil)
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
println("Loaded notes.plist file is --> \(resultDictionary?.description)")
var myDict = NSDictionary(contentsOfFile: path)
if let dict = myDict {
//load values
} else {
println("worning ccould not create dictionary from notes.plist, default values will be used")
}
}
Apple wants you to use URLs instead of paths so they have made it unavailable in Swift 2. If you don't want to use NSURL, you can temporarily cast it to NSString instead:
let path = (DocumentsDirectory as NSString).stringByAppendingPathComponent("notes.plist")

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