How to save selected image from photo gallery to show any view controller in swift - swift

I'm working on my app and i got stuck at one point.
There is one UIIMAGEVIEW and one UPLOAD button.
So when user click UPLOAD button he get to photo gallery to select image after selecting image I'm showing that image on UIIMAGEVIEW.
So my question is:-
after showing image on UIIMAGEVIEW i want to save that image on app to show that same image on different View Controller.

In this case you can try this code snippet:
func saveImgToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = "image.png" // image name for identify particular image
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = UIImageJPEGRepresentation(image, 1.0),!FileManager.default.fileExists(atPath: fileURL.path){
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
func loadImgFromDocumentDirectory(nameOfImage : String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
let image = UIImage(contentsOfFile: imageURL.path)
return image!
}
return UIImage.init(named: "default.png")!
}
Image name is a unique identifier for the image, while storing you are required to specify the image name "imageName", so it would be easy to fetch that particular image using the same name.

You can put the image in a global variable. A global variable can be used through all the app. :
var imageSelected:UIImage? // Value will be nil if no image has been set
class ViewController1 {
// Puts your image inside a global variable
image = yourImage
}
class ViewController2 {
// Uses the image that was defined inside the global variable
#IBOutlet weak var imageView: UIView!
imageView.image = imageSelected
}

Related

Problem trying to load a set of image using an array of UIImage to slide them

I'm trying to load a set of pictures to an imageView so that they slide alon with a time timer.
My problem is that I have the pictures store in Firebase with their URL as Strings. So I use a function to load a single image throug its URL into an imageView and it works. But now I need to find a way to use a function to put a set of images into the imageView so that the slide with a timer and I donĀ“t now how to do it.
This is the code to load the images from URL
import UIKit
extension UIImageView {
func loadFrom(URLAddress: String) {
guard let url = URL(string: URLAddress) else {
return
}
DispatchQueue.main.async { [weak self] in
if let imageData = try? Data(contentsOf: url) {
if let loadedImage = UIImage(data: imageData) {
self?.image = loadedImage
}
}
}
}
}
Here is the code to load the set of image as an UIImage array.
override func viewWillAppear(_ animated: Bool) {
let even = eventos.eventoPulsado()
var images = [UIImage]()
print(even.imagenes!)
//I load the picture this way
imgFoto.loadFrom(URLAddress: (even.imagenes![0]))
//But I cannot to append my images because I need UIImage data
images.append(imgFoto.image!)
for img in (even.imagenes!) {
imgFoto.loadFrom(URLAddress: (img))
}
imgFoto.animationImages = images
imgFoto.animationDuration = TimeInterval(0.4)
imgFoto.animationRepeatCount = 4
imgFoto.startAnimating()
}

Save GIF Image in Photo Gallery from UIImageView

I have UIImageView which is displaying GIF image, now I am unable to save GIF image into photo gallery.
I am using below swift code
guard let image = imageView.image else { return }
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(savedImage),
nil);
When I use above code it only save single image in photo gallery not saving as GIF.
Suggestion required, how to save GIF loaded from URL or available in the UIImageView into Gallery.
First your need to get all images of gif from imageView and the duration of the image, now you can generate the gif and save in document directory. Finally, save the file from URL to Photo Album
import ImageIO
import Photos
import MobileCoreServices
#IBAction func btnSaveGifFilePressed(_ sender: Any) {
if let imgs = self.imgView.image?.images, imgs.count > 0 {
var animationDuration = self.imgView.image?.duration ?? 1.0
animationDuration = animationDuration / Double(imgs.count);
let url = FileManager.default.urlForFile("lion.gif")
FileManager.default.createGIF(with: imgs, url: url, frameDelay: animationDuration)
PHPhotoLibrary.shared().performChanges ({
PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
}) { saved, error in
if saved {
print("Your image was successfully saved")
}
}
}
}
Create GIF using the following code.
func createGIF(with images: [UIImage], url: URL, frameDelay: Double) {
if let destinationGIF = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, images.count, nil) {
let properties = [
(kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): frameDelay]
]
for img in images {
let cgImage = img.cgImage
CGImageDestinationAddImage(destinationGIF, cgImage!, properties as CFDictionary?)
}
CGImageDestinationFinalize(destinationGIF)
}
}
Get a URL in single line:
func urlForFile(_ fileName: String, folderName: String? = nil) -> URL {
var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
if let folder = folderName {
documentsDirectory = documentsDirectory.appendingPathComponent(folder)
if !self.fileExists(atPath: documentsDirectory.path) {
try? self.createDirectory(atPath: documentsDirectory.path, withIntermediateDirectories: true, attributes: nil)
}
}
let fileURL = documentsDirectory.appendingPathComponent(fileName)
return fileURL;
}

loadImageFromDisk - function modyfication swift

im using the below code to load a downloaded image from disk, when the file exists I can load it as image. If it doesn't image returns as nil.
How could I modify the code to replace return nil with loading a placeholder image from my asset folder called default.png. So instead of returning nil, there is always an image return, either downloaded one that's trying to load or if it doesn't exist, my own asset image.
func loadImageFromDiskWith(fileName: String) -> UIImage? {
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath = paths.first {
let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
let image = UIImage(contentsOfFile: imageUrl.path)
return image
}
return nil
}
You can do as below -
func loadImageFromDiskWith(fileName: String) -> UIImage {
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
var image = UIImage(named: "default") // Make sure there must be "default.png" in your main bundle.
if let dirPath = paths.first {
let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
if FileManager.default.fileExists(atPath: imageUrl.path) { //Check here for file existence. It won't crash.
image = UIImage(contentsOfFile: imageUrl.path)
}
}
return image
}

How To Add A Image In CoreData And How to Save The Image In CoreData [duplicate]

This question already has answers here:
Saving Picked Image to CoreData
(2 answers)
Closed 4 years ago.
How to add an image in core data? The image type what that I have selected. And how to save the core data image. How can I add a image?
Step 1:- Save the image in Document Directory
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
let newPath = path.appendingPathComponent("image.jpg") //Possibly you Can pass the dynamic name here
// Save this name in core Data using you code as a String.
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
do {
try jpgImageData!.write(to: newPath)
} catch {
print(error)
}
}}
Step:-2: Fetch the Image back from the Document Directory and display index path row wise in table view cell.
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image.png") //Pass the image name fetched from core data here
let image = UIImage(contentsOfFile: imageURL.path)
cell.imageView.image = image
}
This is simple and More convenient Method

Save UIImage array to disk

I have a UIImage array that I'm trying to save to disk (documents directory). I've converted it to Data so it can be saved but I can't figure out the correct/best way to save that [Data] to disk.
(arrayData as NSArray).write(to: filename, atomically: false) doesn't seem right or there seems like there is some better way.
Code so far:
// Get the new UIImage
let image4 = chartView.snapShot()
// Make UIImage into Data to save
let data = UIImagePNGRepresentation(image4!)
// Add Data image to Data Array
arrayData.append(data!)
// Get Disk/Folder
let filename = getDocumentsDirectory().appendingPathComponent("images")
// This is how I'd Write Data image to Disk
// try? data?.write(to: filename)
// TODO: Write array Data images to Disk
(arrayData as NSArray).write(to: filename, atomically: false)
To save your images to the document directory, you could start by creating a function to save your image as follows. The function handles creating the image name for you and returns it.
func saveImage(image: UIImage) -> String {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let uuid = NSUUID().uuidString + ".png"
let fullPath = docs.appendingPathComponent(uuid)
_ = imageData.write(toFile: fullPath, atomically: true)
return uuid
}
Now since you want to save an array of images, you can simply loop and call the saveImage function:
for image in images {
saveImage(image: image)
}
If you prefer to name those images yourself, you can amend the first function to the following:
func saveImage(image: UIImage, withName name: String) {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let name = name
let fullPath = docs.appendingPathComponent(name)
_ = imageData.write(toFile: fullPath, atomically: true)
}
When you save an image as a UIImagePNGRepresentation as you are trying to do, please note that is does not save orientation for you. This means that when you attempt to retrieve the image, it might be titled to the left. You will need to redraw your image to make sure it has the right orientation as this post will explain how to save png correctly. However, if you save your image with UIImageJPEGRepresentation you will not have to worry about all that and you can simply save your image without any extra effort.
EDITED TO GIVE ARRAY OF IMAGES
To retrieve the images you have saved, you can use the following function where you pass an array of the image names and you get an array back:
func getImage(imageNames: [String]) -> [UIImage] {
var savedImages: [UIImage] = [UIImage]()
for imageName in imageNames {
if let imagePath = getFilePath(fileName: imageName) {
savedImage.append(UIImage(contentsOfFile: imagePath))
}
}
return savedImages
}
Which relies on this function to work:
func getFilePath(fileName: String) -> String? {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
var filePath: String?
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0] as NSString
filePath = dirPath.appendingPathComponent(fileName)
}
else {
filePath = nil
}
return filePath
}
You can below code to stored image into local.
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("ImageName.png")
let image = YOUR_IMAGE_TO_STORE.
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)