If I use the image before it is saved it is normal. But if I save it and use it later is is 90 degrees turned. How can I make sure it doesn't save sideways?
func saveEvent(_ center1: CLLocation, title2: String, imagePicked1: UIImage)
{
let data = UIImagePNGRepresentation(imagePicked1);///
let url = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(NSUUID().uuidString+".dat")
do {
try data!.write(to: url!, options: [])
} catch let e as NSError {
print("Error! \(e)");
return
}
let image11 = CKAsset(fileURL: url!)
self.eventRecord.setObject(image11 as CKAsset, forKey: "Picture")
let publicData = CKContainer.default().publicCloudDatabase
publicData.save(self.eventRecord, completionHandler: { record, error in
if error == nil
{
print("Image saved")
}else{
print(error!)
}
})
}
If you need to save your PNG with correct rotation you will need to redraw your image if its orientation it is not .up. You can redraw it as follow:
extension UIImage {
func png(isOpaque: Bool = true) -> Data? { flattened(isOpaque: isOpaque)?.pngData() }
func flattened(isOpaque: Bool = true) -> UIImage? {
if imageOrientation == .up { return self }
UIGraphicsBeginImageContextWithOptions(size, isOpaque, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
edit/update:
For iOS10+ tvOS10+ you can use UIGraphicsImageRenderer:
extension UIImage {
func png(isOpaque: Bool = true) -> Data? { flattened(isOpaque: isOpaque).pngData() }
func flattened(isOpaque: Bool = true) -> UIImage {
if imageOrientation == .up { return self }
let format = imageRendererFormat
format.opaque = isOpaque
return UIGraphicsImageRenderer(size: size, format: format).image { _ in draw(at: .zero) }
}
}
Playground testing:
Usage for images without transparency:
let image = UIImage(data: try! Data(contentsOf: URL(string: "https://i.stack.imgur.com/varL9.jpg")!))!
if let data = image.png() {
let imageFromPNGData = UIImage(data: data)
}
With transparency :
if let data = image.png(isOpaque: false) {
let imageFromPNGData = UIImage(data: data)
}
Just convert the image to JPEG data instead. No need to redraw your image:
let imageData = image.jpegData(compressionQuality: 1.0)
You can use this as well to prevent it from changing of orientation.
func rotateImage(image: UIImage) -> UIImage? {
if (image.imageOrientation == UIImage.Orientation.up ) {
return image
}
UIGraphicsBeginImageContext(image.size)
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let copy = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return copy
}
Related
I need to be able to load an heic image and extract and output all of the sub images as pngs similar to how preview does it. For example, if you open a dynamic heic wallpaper in preview, it shows all the images in the sidebar with their names:
How do you do this? I've tried to use NSImage like below. But that only outputs a single image:
let image = NSImage(byReferencing: url)
image.writePNG(toURL: newUrl)
You need to load the HEIC data, get its CGImageSource and its count. Then create a loop from 0 to count-1 and get each image at the corresponding index. You can create an array with those CGImages in memory or write them to disk (preferred). Note that this will take a while to be executed because of the size of the HEIC file 186MB. Each image extracted will be from 19MB to 28MB.
func extractHeicImages(from url: URL) throws {
let data = try Data(contentsOf: url)
let location = url.deletingLastPathComponent()
let pathExtension = url.pathExtension
let fileName = url.deletingPathExtension().lastPathComponent
let destinationFolder = location.appendingPathComponent(fileName)
guard pathExtension == "heic", let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else { return }
let count = CGImageSourceGetCount(imageSource)
try FileManager.default.createDirectory(at: destinationFolder, withIntermediateDirectories: false, attributes: nil)
for index in 0..<count {
try autoreleasepool {
if let cgImage = CGImageSourceCreateImageAtIndex(imageSource, index, nil) {
let number = String(format: "#%05d", index)
let destinationURL = destinationFolder
.appendingPathComponent(fileName+number)
.appendingPathExtension(pathExtension)
try NSImage(cgImage: cgImage, size: .init(width: cgImage.width, height: cgImage.height))
.heic?
.write(to: destinationURL)
print("saved image " + number)
}
}
}
}
You will need these helpers as well to extract the cgimate from your image and also to get a HEIC data representation from them:
extension NSImage {
var heic: Data? { heic() }
var cgImage: CGImage? {
var rect = NSRect(origin: .zero, size: size)
return cgImage(forProposedRect: &rect, context: .current, hints: nil)
}
func heic(compressionQuality: CGFloat = 1) -> Data? {
guard
let mutableData = CFDataCreateMutable(nil, 0),
let destination = CGImageDestinationCreateWithData(mutableData, "public.heic" as CFString, 1, nil),
let cgImage = cgImage
else { return nil }
CGImageDestinationAddImage(destination, cgImage, [kCGImageDestinationLossyCompressionQuality: compressionQuality] as CFDictionary)
guard CGImageDestinationFinalize(destination) else { return nil }
return mutableData as Data
}
}
Playground testing. This assumes the "Catalina.heic" is located at your desktop.
let catalinaURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!.appendingPathComponent("Catalina.heic")
do {
try extractHeicImages(from: catalinaURL)
} catch {
print(error)
}
Each subimage is represented by a NSBitmapImageRep. Loop the image reps, convert to png and save:
let imageReps = image.representations
for imageIndex in 0..<imageReps.count {
if let imageRep = imageReps[imageIndex] as? NSBitmapImageRep {
if let data = imageRep.representation(using: .png, properties: [:]) {
do {
let url = folderURL.appendingPathComponent("image \(imageIndex).png", isDirectory: false)
try data.write(to: url, options:[])
} catch {
print("Unexpected error: \(error).")
}
}
}
}
The conversion to png takes some time. Running the conversions in parallel is faster but I'm not sure if it's save:
DispatchQueue.concurrentPerform(iterations: imageReps.count) { iteration in
if let imageRep = imageReps[iteration] as? NSBitmapImageRep {
if let data = imageRep.representation(using: .png, properties: [:]) {
do {
let url = folderURL.appendingPathComponent("image \(iteration).png", isDirectory: false)
try data.write(to: url, options:[])
} catch {
print("Unexpected error: \(error).")
}
}
}
}
what im trying to achieve is to have custom profile IMG on a tabbar item
First: I have tried to add the IMG to the tabbar directly
let ProfileImg: UIImageView = {
let Img = UIImageView(image: UIImage(named: "PlaseHolder"))
Img.layer.cornerRadius = 20
Img.contentMode = .scaleAspectFit
Img.clipsToBounds = true
Img.layer.masksToBounds = true
Img.translatesAutoresizingMaskIntoConstraints = false
return Img
}()
override func viewDidLoad() {
super.viewDidLoad()
fetchUser()
}
func fetchUser() {
guard let uid = Auth.auth().currentUser?.uid else {return}
let userRef = Database.database().reference(withPath: "users").child(uid)
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot.value ?? "")
let value = snapshot.value as? NSDictionary
guard let profileImageUrl = value?["profileImageUrl"] as? String else {return}
guard let url = URL(string: profileImageUrl) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
if let err = err {
print("unable to get profile image", err)
}
guard let data = data else {return}
let image = UIImage(data: data)
DispatchQueue.main.async {
self.tabBarItem.image = image?.withRenderingMode(.alwaysOriginal)
self.tabBarItem.selectedImage = image?.withRenderingMode(.alwaysOriginal)
}
}.resume()
}) { (err) in
print("fail to fetch user", err)
}
}
and this was the result :
iphone simulator image
the image is too big for a tabbar item image
but then I found another method I couldn't dead it or get it, it did add the image but I couldn't make it fit inside the tabbar + the corner radius is not working
extension UITabBarController {
func addSubviewToLastTabItem(_ imageName: UIImage) {
if let lastTabBarButton = self.tabBar.subviews.last, let tabItemImageView = lastTabBarButton.subviews.last {
if let accountTabBarItem = self.tabBar.items?.first {
accountTabBarItem.selectedImage = nil
accountTabBarItem.image = nil
}
let imgView = UIImageView()
imgView.frame = tabItemImageView.frame
imgView.layer.cornerRadius = tabItemImageView.frame.height/2
imgView.layer.masksToBounds = true
imgView.contentMode = .scaleAspectFill
imgView.clipsToBounds = true
imgView.image = imageName
self.tabBar.subviews.last?.addSubview(imgView)
}
}
}
and this is how to call it
self.tabBarController?.addSubviewToLastTabItem(image!)
Result : iphone simulator image
please any idea to accomplish this
use this extintion to resize your image
extension UIImage {
func resize(targetSize: CGSize) -> UIImage {
return UIGraphicsImageRenderer(size:targetSize).image { _ in
self.draw(in: CGRect(origin: .zero, size: targetSize))
}
}
}
here is how to use it in dispatch method
DispatchQueue.main.async { [weak self] in
guard let data = data else {return}
self?.ProfileImg.image = UIImage(data: data)?.resize(targetSize: CGSize(width: 33, height: 33)).roundMyImage.withRenderingMode(.alwaysOriginal)
self?.tabBar.items?[0].selectedImage = self?.ProfileImg.image
self?.tabBar.items?[0].image = self?.ProfileImg.image
}
}.resume()
Good evening
I am trying to save the resized images in Documents Directory, to avoid having to resize every time it is called.
Analyzing the problem is just when I use the following line:
let jpgImageData = UIImageJPEGRepresentation (image, 1.0)
It appears that UIImageJPEGRepresentation undoes the changes made to the image and thus saves the image in the same ratio.
Anyone know a way to fix this?
Below the code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let myImageName = "image_10001.jpg"
let imagePath = fileInDocumentsDirectory(filename: myImageName)
if let image = UIImage(named:"image_10001")?.resizedImage(newSize: UIScreen.main.bounds.size){
print("Image : \(image.size.height)")
_ = saveImage(image: image, path: imagePath)
}
if let loadedImage = loadImageFromPath(path: imagePath){
print("Screen: \(UIScreen.main.bounds.size.height)")
print("Image Size: \(loadedImage.size.height)")
// let image = UIImageJPEGRepresentation(loadedImage, 0.9)
// let imgRes = UIImage(data: image!)?.resizedImage(newSize: UIScreen.main.bounds.size)
////
// let load = loadedImage.resizedImage(newSize: UIScreen.main.bounds.size)
//
// print("Load: \(load.size.height)")
//
// _ = saveImage(image: load, path: imagePath)
//
imgView.image = loadedImage
//
// imgView.image = UIImage(data: image!)?.resizedImage(newSize: UIScreen.main.bounds.size)
}
// Do any additional setup after loading the view, typically from a nib.
}
func loadImageFromPath(path: String) -> UIImage? {
let image = UIImage(contentsOfFile: path)
if image == nil {
print("missing image at: \(path)")
}
print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
return image
}
func getDocumentsURL() -> URL {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
return documentsURL
}
func fileInDocumentsDirectory(filename: String) -> String {
let fileURL = getDocumentsURL().appendingPathComponent(filename)
return fileURL.path
}
func saveImage (image: UIImage, path: String ) -> Bool{
print("Save")
let url = URL(fileURLWithPath: path)
// let pngImageData = UIImagePNGRepresentation(image)
let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG
let img = UIImage(data:jpgImageData!)
//
print("SIMG: \(String(describing: img?.size.height))")
do {
_ = try jpgImageData?.write(to: url, options: .atomicWrite)
print("Save Success")
} catch let error {
print(error)
return false
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UIImage {
/// Returns a image that fills in newSize
func resizedImage(newSize: CGSize) -> UIImage {
// Guard newSize is different
guard self.size != newSize else { return self }
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
self.draw(in: CGRect(x:0, y:0, width:newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// Returns a resized image that fits in rectSize, keeping it's aspect ratio
/// Note that the new image size is not rectSize, but within it.
func resizedImageWithinRect(rectSize: CGSize) -> UIImage {
let widthFactor = size.width / rectSize.width
let heightFactor = size.height / rectSize.height
var resizeFactor = widthFactor
if size.height > size.width {
resizeFactor = heightFactor
}
let newSize = CGSize(width:size.width/resizeFactor, height:size.height/resizeFactor)
let resized = resizedImage(newSize: newSize)
return resized
}
var jpeg: Data? {
return UIImageJPEGRepresentation(self, 1) // QUALITY min = 0 / max = 1
}
var png: Data? {
return UIImagePNGRepresentation(self)
}
}
extension Data {
var uiImage: UIImage? {
return UIImage(data: self)
}
}
I assume you have some "old" image inside your documents directory that was saved with some older code you had (not resized).
I assume that because the code you posted will not save any new images, because of this line:
if let image = UIImage(named:"image_10001")?.resizedImage(newSize: UIScreen.main.bounds.size){
//resize code
}
I think you wanted to use here same image name just taken from bundle:
if let image = UIImage(named: myImageName)?.resizedImage(newSize: UIScreen.main.bounds.size){
//resize code
}
You can Reset Simulator Content and confirm that no image will be loaded with the code you posted here.
I would like to enhance the code below to cache images and only download them if they haven't been cached previously. I can't seem to find any good examples of how to use URLSession object to do this.
extension UIImageView {
func loadImageWithURL(_ url: URL) -> URLSessionDownloadTask {
let session = URLSession.shared
let downloadTask = session.downloadTask(with: url, completionHandler: { [weak self] url, response, error in
if error == nil, let url = url,
let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
if let strongSelf = self {
strongSelf.image = image
}
}
}
})
downloadTask.resume()
return downloadTask
}
}
Updated for Swift 4
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
class ImageLoader: UIImageView {
var imageURL: URL?
let activityIndicator = UIActivityIndicatorView()
func loadImageWithUrl(_ url: URL) {
// setup activityIndicator...
activityIndicator.color = .darkGray
addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
imageURL = url
image = nil
activityIndicator.startAnimating()
// retrieves image if already available in cache
if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage {
self.image = imageFromCache
activityIndicator.stopAnimating()
return
}
// image does not available in cache.. so retrieving it from url...
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
print(error as Any)
DispatchQueue.main.async(execute: {
self.activityIndicator.stopAnimating()
})
return
}
DispatchQueue.main.async(execute: {
if let unwrappedData = data, let imageToCache = UIImage(data: unwrappedData) {
if self.imageURL == url {
self.image = imageToCache
}
imageCache.setObject(imageToCache, forKey: url as AnyObject)
}
self.activityIndicator.stopAnimating()
})
}).resume()
}
}
Usage:
// assign ImageLoader class to your imageView class
let yourImageView: ImageLoader = {
let iv = ImageLoader()
iv.frame = CGRect(x: 10, y: 100, width: 300, height: 300)
iv.backgroundColor = UIColor(red: 0.94, green: 0.94, blue: 0.96, alpha: 1.0)
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
// unwrapped url safely...
if let strUrl = "https://picsum.photos/300/300".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let imgUrl = URL(string: strUrl) {
yourImageView.loadImageWithUrl(imgUrl) // call this line for getting image to yourImageView
}
One potential solution to this would be to utilize NSCache to take care of caching. Essentially what you would do is check if you already have the image locally to load from rather than fetching every time before you actually make a request.
Here's one of my implementations, however - it's a subclass rather than an extension:
class CustomImageView: UIImageView {
// MARK: - Constants
let imageCache = NSCache<NSString, AnyObject>()
// MARK: - Properties
var imageURLString: String?
func downloadImageFrom(urlString: String, imageMode: UIViewContentMode) {
guard let url = URL(string: urlString) else { return }
downloadImageFrom(url: url, imageMode: imageMode)
}
func downloadImageFrom(url: URL, imageMode: UIViewContentMode) {
contentMode = imageMode
if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) as? UIImage {
self.image = cachedImage
} else {
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async {
let imageToCache = UIImage(data: data)
self.imageCache.setObject(imageToCache!, forKey: url.absoluteString as NSString)
self.image = imageToCache
}
}.resume()
}
}
}
Additionally, here's a useful resource:
https://www.hackingwithswift.com/example-code/system/how-to-cache-data-using-nscache
URLSession DataTask by default will cache the image automatically and you don't need to do anything on client-side as long as the cache setting on the server is normal. Images are static assets and won't change in short time, as the result, server will normally set "Cache-Control" to "public, max-age:xxxxx". URLSession default cache policy will cache the image both in memory and disk. However, it won't cache the image whose size is larger than 5% of disk size allocated for URLCache, and it doesn't do caching in background thread either.
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageFromUrl(urlString: String) {
if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage{
self.image = imageFromCache
return
}
Alamofire.request(urlString, method: .get).response { (responseData) in
if let data = responseData.data {
DispatchQueue.main.async {
if let imageToCache = UIImage(data: data){
imageCache.setObject(imageToCache, forKey: urlString as AnyObject)
self.image = imageToCache
}
}
}
}
}
}
the code I currently have gets a profile picture from firebase and displays it on the map as the marker icon.
self.ref.child("users").child(location.key as! String).child("userPhoto").observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
if(snapshot.exists()) {
let profileUrl = snapshot.value as? String
let url = NSURL(string: profileUrl!)
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(), {
if let downloadedImage = UIImage(data: data!) {
marker.icon = downloadedImage
}
})
}).resume()
}
})
Unfortunately, this code just plops a really big image on the map which i dont want. i want a circular image with a border/background that makes it look like a pin/marker. Like this:
Ideal Deign of The Marker Icon
Would anyone know how to do this?
Any help would be appreciated.
Thanks!
P.S: I am new to swift and would really appreciate if you could show me some code with whatever solution you provide. Thanks!
func changeImageDimensions(image: UIImage, newWidth: CGFloat, newHeight: CGFloat) -> UIImage {
let widthRat = newWidth/image!.size.width
let heightRat = newHeight/image!.size.height
var newSize: CGSize = CGSize()
if(widthRat > heightRat) {
newSize = CGSizeMake(image!.size.width * heightRat, image!.size.height * heightRat)
} else {
newSize = CGSizeMake(image!.size.width * widthRat, image!.size.height * widthRat)
}
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
let frameRect = CGRectMake(0, 0, newSize.width, newSize.height)
image.drawInRect(frameRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
self.ref.child("users").child(location.key as! String).child("userPhoto").observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
if(snapshot.exists()) {
let profileUrl = snapshot.value as? String
let url = NSURL(string: profileUrl!)
NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) in
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(), {
if let downloadedImage = UIImage(data: data!) {
marker.icon = changeImageDimensions (downloadedImage!,newWidth:CGFloat(150),newHeight:CGFloat(150))
}
})
}).resume()
}
})