I have a Swift 4.1 (Xcode 9.3) Playground with these contents, and it's failing in a non-obvious way.
import UIKit
let url: URL = URL(string: "https://placekitten.com/500/500")!
let image: CIImage = CIImage(contentsOf: url)!
The resulting error is Failed to convert UIImage to PNG. For completeness, the returned place kitten is a JPG image.
Whereas I cannot tell you the reason, for why your code does not work as expected, you can use the following workaround to retrieve a CIImage located at a specific URL as suggested in the comments:
import UIKit
let url: URL = URL(string: "https://placekitten.com/500/500")!
let image = UIImage.init(data: try! Data.init(contentsOf: url))!
let convertedImage = CIImage.init(image: image)
Don't forget to add adequate error handling. I left that out for the sake of simplicity
Related
When the user selects an item from their photo library, the app saves the UIImage to the app's directory using the following code:
let imageUUID = UUID()
let filename = getDocumentsDirectory().appendingPathComponent("\(imageUUID)")
guard let uiImage = newImage else { return}
if let jpegData = uiImage.jpegData(compressionQuality: 0.8) {
try? jpegData.write(to: filename, options: [.atomicWrite, .completeFileProtection])
}
How can I use the saved image in a view?
Thanks!
First, you should save the UUID somewhere so that you can read the file later. This could be in UserDefaults, a JSON file, CoreData, or whatever, depending on your needs.
Suppose you have the path to the file stored in filePath, you can create an Image like this:
Image(uiImage: UIImage(contentsOfFile: filePath) ?? UIImage())
This will use an empty image as fallback if it failed to read the file.
Following code convert UIImage to Image in SwiftUI:
let uiImage = UIImage(contentsOfFile: path) ?? UIImage() // Access it from your storage
let image = Image(uiImage: uiImage)
There are different UIImage initializer methods available, you can use any one of them to get UIImage instance.
https://developer.apple.com/documentation/swiftui/image
You will like this tutorial of Coredata with SwiftUI: https://www.raywenderlich.com/9335365-core-data-with-swiftui-tutorial-getting-started
I'm new in the Swift, I am using Alamofire framework in my project, I am facing the following issue while giving the request for download image, I am using following code:
let imageURL = Constant.BaseAPI_URL + "/" + driver.driverProfile
Alamofire.request(.GET, imageURL).response() {
(_, _, data, _) in
let image = UIImage(data: data! as! NSData)
deiverProfileImageView.image = image
}
Issue :
Click Here For Image Description
Try this:
let imageURL = Constant.BaseAPI_URL + "/" + driver.driverProfile
Alamofire.download(imageURL).responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
deiverProfileImageView.image = image
}
}
Try below code
let imageURL = Constant.BaseAPI_URL + "/" + driver.driverProfile
Alamofire.request(imageURL).responseData(completionHandler: { response in
if let imageData = response.data
{
deiverProfileImageView.image = imageData
}
})
Try this:
let imageUrl = "www.your_url.com"
Alamofire.download(imageUrl).responseData {
response in
if let data = response.result.value {
let image = UIImage(data: data)
ProfileImage.image = image
}
}
or
The easiest way according to me will be using SDWebImage
Add this to your pod file
pod 'SDWebImage', '~> 4.0'
Run pod install
Now import SDWebImage
import SDWebImage
Now for setting image from url
imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash
This are the main feature of SDWebImage
Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC
To know more https://github.com/rs/SDWebImage
Using Swift 3 for iOS, I am able to use cinemagraphs (animated gifs) that I download through a UIWebView without any problem. I am also trying to get them to work from the iPhone library. However, there is no way that I have found to get the data representation of a GIF stored in the library.
Someone will say that "there is no such thing as an animated gif in the library", but they would be wrong. Go to a web page in Safari, long-tap on an animated gif, and save it to your library. Then send a text message to yourself and copy in that image from the library. You'll see that the animated gif is intact and works perfectly.
My problem is that I need to copy the image from the library programmatically, and I'm not sure how to do it with no specific function built for GIFs. I would like to create the equivalent of UIImagePNGRepresentation or UIImageJPEGRespresentation, except for GIF images. Alternatively, is there a way to get an image from the library as a UIImage, so I don't have to try to convert it to data?
Here's the code I am using for other image formats:
* Edited to be latest version *
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let origImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let refURL : URL = info[UIImagePickerControllerReferenceURL] as! URL
var resizedImage: UIImage!
var ext: String!
ext = refURL.pathExtension
if ext == "GIF" {
resizedImage = origImage
} else {
resizedImage = resizeImage(origImage: origImage, ext: ext)
}
DispatchQueue.main.async(execute: { () -> Void in
self.photoUpdated(newImage: resizedImage)
})
picker.dismiss(animated: true, completion: nil)
}
For GIFs, I tried the following, using the SwiftGif project, which was not successful:
let url = Bundle.main.url(forResource: refURL.absoluteString, withExtension: "GIF")
let data = try! Data(contentsOf: url!)
let advTimeGif = UIImage.gifWithData(data)
let imageView = UIImageView(image: advTimeGif)
newImage = imageView.image
Anyone have any suggestions as to how I might get this to work? Thanks.
Edit:
I figured out a few more pieces of the puzzle. Specifically, I can get the image name and the local path to it.
let refURL : URL = info[UIImagePickerControllerReferenceURL] as! URL
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
let localPath = URL(fileURLWithPath: documentDirectory).appendingPathComponent(imageName)
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
Still can't figure out how to get it from there to Data.
I am developing some tumblr client. And i want to download all photos in dashboard and save them to documentDirectory. Some of them is jpg some are gif. I have successfully download jpg images with this code:
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(fname)
if let pngImageData = UIImagePNGRepresentation(myImage!) {
try pngImageData.write(to: fileURL, options: .atomic)
print(fname + " - saved")
}
} catch {print(fname + " - not saved") }
myImage is the image which is downloaded from URL. This code is work for jpg images but not good for gifs.
And lastly i read these files with this:
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filePath = documentsURL.appendingPathComponent(fname).path
if FileManager.default.fileExists(atPath: filePath) {
return UIImage(contentsOfFile: filePath)!
}
It's work for jpg but not for gifs. when i try this writing/reading codes on gifs images, i got just image not animation.
Can you show me the way pls with an example will be awesome.
Thank you.
I personally used this tinnie tool for GIFs. Simply add the iOSDevCenters+GIF.swift file directly to your project and use it as shown below
1. Online URL
let imageURL = UIImage.gifImageWithURL(gifURL)
let yourImageView = UIImageView(image: imageURL)
2. Local Filename
let imageName = UIImage.gifImageWithName(imageName)
let yourImageView = UIImageView(image: imageName)
3. Using Data
let imageData = NSData(contentsOf: Bundle.main.url(forResource: "name", withExtension: ".gif"))
let imageData = UIImage.gifImageWithData(imageData)
let yourImageView = UIImageView(image: imageData)
Actually your first code is not working correctly either.
What you are receiving is the image. You do not need or want to translate it into some other kind of image (UIImagePNGRepresentation). Just save the data. Later, read the data directly into a UIImage.
I think there is no problem with downloading and you are just trying to present it as a png; instead try to present this saved data with this library, for example
Try this:
#import AssetsLibrary
let lib = ALAssetsLibrary()
let data = NSData(contentsOfURL: getCurrentGIFURL)
lib.writeImageDataToSavedPhotosAlbum(data, metadata: nil) { (url, err) in
}
This question already has answers here:
Transport security has blocked a cleartext HTTP
(29 answers)
Closed 6 years ago.
When I try to load an image from a URL I always get an error despite the fact that I know that there is a URL that contains a valid .jpg image.
mainImageView.image = try UIImage(data: Data(contentsOf: URL(fileURLWithPath: artworkURL)))
I also tried these solution but the line where I initialise the UIImage still throws an error.
Example of data in artworkURL:
http://is1.mzstatic.com/image/thumb/Music/v4/ef/97/95/ef979538-8321-151a-dceb-9b0a7f7c7641/source/100x100bb.jpg
Current solutions do not solve my problem. I also tried:
try UIImage(data: Data(contentsOf: URL(string: artworkURL)!))
and
try UIImage(data: Data(contentsOf: (URL : artworkURL)))
and (fuller code) now using a static url to debug
let artworkString = "http://is1.mzstatic.com/image/thumb/Music/v4/ef/97/95/ef979538-8321-151a-dceb-9b0a7f7c7641/source/100x100bb.jpg" // album.artworkURL[index.row]
let url = URL(string: artworkString)
do {
mainImageView.image = try UIImage(data: Data(contentsOf: url!))
} catch _ {
print("No album artwork!")
}
This last one outputs "No album artwork!"!
You can user this library:
https://github.com/onevcat/Kingfisher
Kingfisher is a lightweight, pure-Swift library for downloading and caching images from the web. This project is heavily inspired by the popular SDWebImage. It provides you a chance to use a pure-Swift alternative in your next app.
let imagePath = URL(string: "url_of_your_image")
imageView.kf_setImageWithURL(NSURL(string: imagePath)!, placeholderImage: UIImage(named: "placeholder"))
you can also add placeholder image.