I'm currently writing a photo app for iOS in Swift. I'm using the CoreImage Framework to generate a pixel effect on a UIImageView selected by the user. However, I'm having trouble saving the "pixeled" image to the iPhone's Camera Roll. Normally I use
UIImageWriteToSavedPhotosAlbum(pixeledImage,nil,nil,nil)
but it's not saving the UIImage. I have given the app full access to the photo library on the device. It will be helpful if someone could help me figure this out. My image picker:
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var imagetobepassed: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func Cameratapped(sender: AnyObject) {
var camera = UIImagePickerController()
dispatch_async(dispatch_get_main_queue()) {
camera.delegate = self
camera.sourceType = UIImagePickerControllerSourceType.Camera
camera.allowsEditing = false
self.presentViewController(camera, animated: true, completion: nil)
}
}
#IBAction func photolib(sender: AnyObject) {
var photo = UIImagePickerController()
dispatch_async(dispatch_get_main_queue()) {
photo.delegate = self
photo.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
photo.allowsEditing = false
self.presentViewController(photo, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imagetobepassed = image
self.dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func editorPressed(sender: AnyObject) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "image" {
var editorview = segue.destinationViewController as! EditorViewController
editorview.imagerecived = imagetobepassed
}
}
}
And my editor:
import UIKit
class EditorViewController: UIViewController {
var imagerecived:UIImage!
var pixeledImage:UIImage!
var savedImage:UIImage!
#IBOutlet var imageview: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
pixel()
}
// this function will prduce the pixel effect
func pixel() {
var regularImage = CIImage(image: imagerecived)
var filter = CIFilter(name: "CIPixellate")
filter.setDefaults()
filter.setValue(regularImage, forKey: kCIInputImageKey)
var output = filter.outputImage
pixeledImage = UIImage(CIImage: output)
imageview.image = pixeledImage
}
#IBAction func SaveTapped(sender: AnyObject) {
println(pixeledImage)
UIImageWriteToSavedPhotosAlbum(pixeledImage,nil,nil,nil) // not saving image
}
How can I make this work? I do see this error:
2015-05-16 23:40:05.416 Pixelate2[21579:3341726] Connection to assetsd
was interrupted or assetsd died
First use this line to save image:-
UIImageWriteToSavedPhotosAlbum(pixeledImage, self, "image:didFinishSavingWithError:contextInfo:", nil)
Now implement this method,to catch the error you are getting:-
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error == nil {
}
else
{
//log the error out here ,if any
}
}
There is another work around, if you are getting memory warning !
ALAssetsLibrary* lib = [[ALAssetsLibrary alloc] init];
[lib writeImageDataToSavedPhotosAlbum:imageData metadata:nil
completionBlock:^(NSURL *assetURL, NSError *error)
{
// do whatever in the completion handler
}];
I was able to solve the issue using this code:
#IBAction func SaveTapped(sender: AnyObject) {
let softwareContext = CIContext(options: [kCIContextUseSoftwareRenderer:true])
let cgimg = softwareContext.createCGImage(savedImage,
fromRect: savedImage.extent())
let libary = ALAssetsLibrary()
libary.writeImageToSavedPhotosAlbum(cgimg, metadata: savedImage.properties(),
completionBlock: nil)
}
Related
I am developing an App that will ask for 5 images, assign them to the proper UIImageViewer for preview purposes, and then I would like to hit upload and all 5 images go to a team drive. At this point all of it works except the code snippet I have is only able to upload images if they are in the App's Documents Directory. I would like to reference back to the 5 previously chosen images and upload them to a team drive but I do not know how to go about that.
Each button has been assigned a tag number, in which will equal their designated UIImageViewer. I am trying to reference the other previously chosen images but an error says in the 'UploadAction' button "Cannot convert value of type 'UIImage' to expected argument type 'String'". Here is my code, any help would be greatly appreciated!! (This is in Swift in Xcode, I could not find any examples using swift to upload pictures using a phone camera or photo gallery)
import UIKit
import GoogleSignIn
import GoogleAPIClientForREST
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, GIDSignInUIDelegate, UIPickerViewDelegate, UITextFieldDelegate{
// func numberOfComponents(in pickerView: UIPickerView) -> Int {
//
// }
// func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//
// }
#IBOutlet weak var imageView1: UIImageView!
#IBOutlet weak var imageView2: UIImageView!
#IBOutlet weak var imageView3: UIImageView!
#IBOutlet weak var imageView4: UIImageView!
#IBOutlet weak var imageView5: UIImageView!
#IBOutlet weak var resultsLabel: UILabel!
var imagePicker = UIImagePickerController()
var imagePicked = 0
var cameraPicker = UIImagePickerController()
var cameraPicked = 0
fileprivate let service = GTLRDriveService()
private var drive: ATGoogleDrive?
override func viewDidLoad() {
super.viewDidLoad()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
cameraPicker.allowsEditing = false; imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false;
GIDSignIn.sharedInstance().uiDelegate = self;
self.view.backgroundColor = UIColor.lightGray;
setupGoogleSignIn()
drive = ATGoogleDrive(service)
}
#IBAction func openCamera(_ sender: UIButton){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
cameraPicked = sender.tag
present(cameraPicker, animated: true)
}
}
#IBAction func chooseImage1(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.savedPhotosAlbum){
imagePicked = sender.tag
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
let cameraImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
if imagePicked == 1 {
imageView1.image = pickedImage
} else if imagePicked == 2 {
imageView2.image = pickedImage
} else if imagePicked == 3 {
imageView3.image = pickedImage
} else if imagePicked == 4 {
imageView4.image = pickedImage
} else if imagePicked == 5 {
imageView5.image = pickedImage
} else if cameraPicked == 6 {
imageView1.image = cameraImage
} else if cameraPicked == 7 {
imageView2.image = cameraImage
} else if cameraPicked == 8 {
imageView3.image = cameraImage
} else if cameraPicked == 9 {
imageView4.image = cameraImage
} else if cameraPicked == 10 {
imageView5.image = cameraImage
}
dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true)
}
private func setupGoogleSignIn() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = [kGTLRAuthScopeDriveFile]
GIDSignIn.sharedInstance().signInSilently()
}
// MARK: - Actions
**#IBAction func uploadAction(_ sender: Any) {
if let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let uploadem = imageView1.image
drive?.uploadFile("agostini_tech_demo", filePath: uploadem, MIMEType: "image/png") { (fileID, error) in
print("Upload file ID: \(fileID); Error: \(error?.localizedDescription)")**
}
}
}
#IBAction func listAction(_ sender: Any) {
drive?.listFilesInFolder("agostini_tech_demo") { (files, error) in
guard let fileList = files else {
print("Error listing files: \(error?.localizedDescription)")
return
}
self.resultsLabel.text = fileList.files?.description
}
}
}
// MARK: - GIDSignInDelegate
extension ViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let _ = error {
// service.authorizer = nil
} else {
// service.authorizer = user.authentication.fetcherAuthorizer()
}
}
}
I have an app where a user takes some pictures which are saved into an array, then when he presses a button i want the array of images to be saved to firebase. I have searched around and not found any good resources for this. Bellow is the code I have already written.
DataModel where I save the array of images:
import Foundation
import UIKit
class PhotoArray {
static let sharedInstance = PhotoArray()
var photosArray: [UIImage] = []
}
Taking picture code:
import UIKit
import RealmSwift
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// var realm: Realm!
// var photoArray = [PhotoArray]()
#IBOutlet weak var imageView: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// realm = try! Realm()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let userPickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// let imageToUse = PhotoArray()
// let data = UIImagePNGRepresentation(userPickedImage) //here convert to data
PhotoArray.sharedInstance.photosArray.append(userPickedImage) //append converted data in array
// do {
// try realm.write {
// realm.add(imageToUse)
// }
// } catch {
// print(“error adding image to array\(error)“)
// }
imageView.image = userPickedImage
}
// print(PhotoArray().photosArray.count)
imagePicker.dismiss(animated: true, completion: nil)
}
#IBAction func cameraButtonPressed(_ sender: UIButton) {
present(imagePicker, animated: true, completion: nil)
}
#IBAction func cameraButtonPressed(_ sender: UIButton) {
present(imagePicker, animated: true, completion: nil)
}
#IBAction func SendDataPressed(_ sender: UIButton) {
//TODO: Send the Images to Firebase and save it in our database
let messagesDB = Database.database().reference().child("Images")
let messageDictionary = ["Images": PhotoArray.sharedInstance.photosArray as NSArray]
messagesDB.childByAutoId().setValue(messageDictionary) {
(error, refrence) in
if error != nil {
print(error!)
//somthing
}
else {
print("message saved succesfully")
//somthing
}
}
}
}
Firebase databases don't support adding images to the database. You can find the supported Firebase data types here.
You should instead upload your images to a storage provider such as Firebase Cloud Storage and then save the url to that file in your database to download from later.
Here's an example:
//Create a reference to the image
let imageRef = Storage.storage().reference().child("image.jpg")
// Get image data
if let uploadData = UIImagePNGRepresentation(userPickedImage) {
// Upload image to Firebase Cloud Storage
imageRef.putData(uploadData, metadata: nil) { (metadata, error) in
guard error == nil else {
// Handle error
return
}
// Get full image url
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Handle error
return
}
// Save url to database
Firestore.firestore().collection("images").document("myImage").setData(["imageUrl" : downloadUrl.absoluteString])
}
}
}
i'm working on this assignment where we have to build a custom camera feature and store images into the phone gallery. So i kinda did almost until the camera preview but i'm not sure yet how to capture and store the images using swift 3.
Here's the source code :
var captureSession = AVCaptureSession()
var sessionOutput = AVCapturePhotoOutput()
var previewLayer = AVCaptureVideoPreviewLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
let deviceSession = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDuoCamera,.builtInTelephotoCamera], mediaType: AVMediaTypeVideo, position: .unspecified)
for device in (deviceSession?.devices)! {
if device.position == AVCaptureDevicePosition.back {
do {
let input = try AVCaptureDeviceInput.init(device: device)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
if captureSession.canAddOutput(sessionOutput) {
captureSession.addOutput(sessionOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.connection.videoOrientation = .portrait
cameraLayerView.layer.addSublayer(previewLayer)
cameraLayerView.addSubview(topControllerView)
cameraLayerView.addSubview(bottomControllerView)
previewLayer.position = CGPoint(x: self.cameraLayerView.frame.width / 2, y: self.cameraLayerView.frame.height / 2)
previewLayer.bounds = cameraLayerView.frame
captureSession.startRunning()
}
}
} catch let avError {
print(avError)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
#IBAction func galleryAction(_ sender: UIButton) {
// This part shows the thumbnail of a current image been taken
}
#IBAction func captureAction(_ sender: UIButton) {
// This is the part i have capture the image
}
Taking the picture it's really simple, take a look here.
To present the image picker:
func takePhoto(sender: UIButton) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
Getting the taken/selected image:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
Now, saving the UIImage to the photo album can be done like explained here.
The following call will save the photo to the gallery and call a completion handler:
UIImageWriteToSavedPhotosAlbum(yourImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
The handler is something like:
func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if let error = error {
// error
} else {
// no error
}
}
Whenever I try to open a different view controller with a show segue it crashes with this error Swift: Thread 1 signal SIGABRT in class AppDelegate: UIResponder, UIApplicationDelegate, I don't know why.
Here's the code of the View Controller that I try to open:
import UIKit
import CoreData
class AddEditVC: UIViewController, NSFetchedResultsControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var item : Item? = nil
#IBOutlet weak var itemName: UITextField!
#IBOutlet weak var imageHolder: UIImageView!
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
if item != nil {
itemName.text = item?.name
imageHolder.image = UIImage(data: (item?.image)!)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImage(sender: AnyObject) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
pickerController.allowsEditing = true
self.presentViewController(pickerController, animated: true, completion: nil)
}
#IBAction func addImageFromCamera(sender: AnyObject) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.Camera
pickerController.allowsEditing = true
self.presentViewController(pickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
self.imageHolder.image = image
}
#IBAction func saveTapped(sender: AnyObject) {
if item != nil {
editItem()
} else {
createNewItem()
}
}
func createNewItem() {
let entityDescription = NSEntityDescription.entityForName("Item", inManagedObjectContext: moc)
let item = Item(entity: entityDescription!, insertIntoManagedObjectContext: moc)
item.name = itemName.text
item.image = UIImagePNGRepresentation(imageHolder.image!)
do {
try moc.save()
} catch {
return
}
}
func editItem () {
item?.name = itemName.text
item!.image = UIImagePNGRepresentation(imageHolder.image!)
do {
try moc.save()
} catch {
return
}
}
This error is usually appears when some of #IBOutlet or #IBAction is not assigned in the MainStoryboard.
Please check small circles before them. They should be grayed
It's either what Andriy is saying, or you executed a PerformSegueWithIdentifier(name, nil) with the wrong identifier. Best to add a screenshot of your storyboard & original controller as well to give a definite answer.
Good luck!
I am trying to make a simple "Profile" view that allows the user to change his picture. the image picker loads the gallery successfully and i choose the new image then write it to documents directory to load it in next launch, the problem is the imageview is not refreshing with the new image until i exit the app and relaunch again (only viewDidLoad works but viewWillAppear is loading the old image although it is overwritten!) any ideas?
import UIKit
class Profile: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var imagePicker:UIImagePickerController=UIImagePickerController()
var pickedImage:UIImage?
let filemgr = NSFileManager.defaultManager()
#IBOutlet weak var profilepic: UIImageView!
#IBOutlet weak var lblheight: UILabel!
#IBOutlet weak var lblwidth: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
profilepic.layer.borderWidth=1
profilepic.layer.borderColor=UIColor.blackColor().CGColor
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
profilepic.userInteractionEnabled = true
profilepic.addGestureRecognizer(tapGestureRecognizer)
imagePicker.delegate=self
if profileImageExists()
{
pickedImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))!
} else {
pickedImage=UIImage(named:"camera.png")!
}
profilepic.image=pickedImage
}
func imageTapped(img: AnyObject)
{
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion:
{
self.lblheight.text="completed"
print ("completed image tab")
}
)
}
override func viewWillAppear(animated: Bool) {
pickedImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))!
profilepic.image=pickedImage
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
profilepic.contentMode = .ScaleToFill
profilepic.image = pickedImage
if let data = UIImagePNGRepresentation(pickedImage) {
let filename = Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png")
data.writeToFile(filename, atomically: true)
}
}
dismissViewControllerAnimated(true, completion: nil)
}
func profileImageExists() -> Bool
{
if let profileImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))
{
return true
}
else
{
return false
}
}
}
Loading an UIImage with init(named:) caches the image. So as long as the image name does not change or the system is emptying the cache (for example when you restart the app) the image will be used from the cache and not loaded again.
Try to use init(contentsOfFile:) instead to load the image.
Try updating your imagePickerController method. You have used pickedImage as an instance variable and an local optional variable. I have used newImage instead.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let newImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
profilepic.contentMode = .ScaleToFill
profilepic.image = newImage
pickedImage = newImage
if let data = UIImagePNGRepresentation(newImage) {
let filename = Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png")
data.writeToFile(filename, atomically: true)
}
}
dismissViewControllerAnimated(true, completion: nil)
}