Append UIImage in an array using for loop - ios

I'm currently working on a application that allows a user to take a multiple images and it'll display it on a iCarousel. I'm not very strong at swift so I don't really know how to do it. My question is, "How do I append and display the image after the user takes a photo?" I'm only allowing a maximum of 3 photos. Here's my codes below:
var imageArray : NSMutableArray = NSMutableArray()
#IBOutlet weak var displayView: iCarousel!
override func viewDidLoad() {
super.viewDidLoad()
imageArray = ["1.jpg", "2.jpg", "3.jpg"]
displayView.type = iCarouselType.coverFlow2
displayView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
var imgView : UIImageView!
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
//let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
if view == nil {
imgView = UIImageView(frame: CGRect(x: 0, y:0, width: 250, height: 250))
imgView.contentMode = .scaleAspectFit
}
else
{
imgView = view as! UIImageView
}
imgView.image = UIImage(named:"\(imageArray.object(at: index))")
imgView.addGestureRecognizer(tapGesture)
tapGesture.numberOfTapsRequired = 1
imgView.isUserInteractionEnabled = true
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imgView.contentMode = .scaleToFill
imgView.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
return imgView
}
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
if (option == .spacing)
{
return value * 1.8
}
return value
}
func numberOfItems(in carousel: iCarousel) -> Int {
return imageArray.count
}
func imageTapped(_ sender: UITapGestureRecognizer)
{
let alert = UIAlertController(title: "Pick Image Source", message: "", preferredStyle: .alert)
let takePhotoBtn = UIAlertAction(title: "Take Photo", style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
})
let galleryBtn = UIAlertAction(title: "Select from Gallery", style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary)
{
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
imagePicker.mediaTypes = ["public.image", "public.movie"] //Remove public.movie later
}
})
let cancelBtn = UIAlertAction(title: "Cancel", style: .default, handler: {(_ action: UIAlertAction) -> Void in
// print("Cancel")
})
alert.addAction(takePhotoBtn)
alert.addAction(galleryBtn)
alert.addAction(cancelBtn)
present(alert, animated: true, completion: { _ in })
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if imageArray.count == 3{
return //you can jump to Show the Carousel here
}
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imgView.contentMode = .scaleToFill
imgView.image = pickedImage
// Add image to Array Here
imageArray.add(image)
}
// you can also show refresh carousel from here so new image is availabe in carousel
picker.dismiss(animated: true, completion: nil)
}
if you are allowing maximum of 3 images then you can also write the checking condition in imageTapped function.

Related

imageview not updated accordingly

i want to create an imageview with photo selected from photo library and display in the scrollview by pushing a button. But the image is not displayed after selection but only display when I push the button again. Can someone help me with this one please?
#IBAction func imageBtnPressed(_ sender: Any) {
imagePicker()
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
func imagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let selectedImage = info[.originalImage] as? UIImage
imageOnCanvas = selectedImage
dismiss(animated: true, completion: nil)
}
Your code does not pause just because the UIImagePickerController is presented. So, let's look at your code:
#IBAction func imageBtnPressed(_ sender: Any) {
imagePicker()
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
func imagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
So that is exactly like saying (substituting the contents of the imagePicker function for the function call):
#IBAction func imageBtnPressed(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
Well, as you can clearly see, you are referring to imageOnCanvas when it has not been set yet. The imagePicker is still showing; the user has not chosen a photo yet. But your code has completely come to an end. You've gone on to add a subview consisting of the image view containing the image that was in imageOnCanvas before the code started.

Creating an image format with an unknown type is an error in swift, check my below code

I choose photos from the photo library, unable to get a photo in the table view.
I got Error:
[Generic] Creating an image format with an unknown type is an error
extension EditProfileViewController: GMPickerDelegate {
func gmPicker(_ gmPicker: GMPicker, didSelect string: String) {
self.genderStr = string
self.tableView.reloadData()
}
func gmPickerDidCancelSelection(_ gmPicker: GMPicker) {
}
fileprivate func setupPickerView() {
picker.delegate = self
picker.config.animationDuration = 0.5
picker.config.cancelButtonTitle = "Cancel"
picker.config.confirmButtonTitle = "Confirm"
picker.config.contentBackgroundColor = UIColor(red: 253/255.0, green: 253/255.0, blue: 253/255.0, alpha: 1)
picker.config.headerBackgroundColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1)
picker.config.confirmButtonColor = UIColor.black
picker.config.cancelButtonColor = UIColor.black
}
}
class EditProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UIPickerViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate{
var picker = GMPicker()
let pickerBgView = UIView(frame: CGRect(x: 0,y: 0,width: 30,height: 250))
var pickerView = UIPickerView()
var addressRecord = [String]()
var image1 = UIImage()
let imagePicker: UIImagePickerController! = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "RoundImgCell", bundle: nil), forCellReuseIdentifier: "CellImg")
pickerView.frame = CGRect(x: 0,y: -20,width: self.view.frame.width,height: 250)//UIPickerView(frame: CGRectMake(0,20,self.view.frame.width,250))
pickerView.delegate = self
pickerBgView.backgroundColor = UIColor.yellow
let toolbar = UIToolbar(frame: CGRect(x: 0,y: 0,width: self.view.frame.width,height: 40))
toolbar.barStyle = .black
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(EditProfileViewController.doneAction))
doneButton.tintColor = UIColor.white
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: #selector(EditProfileViewController.doneAction))
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.done, target: self, action: #selector(EditProfileViewController.cancelAction))
cancelButton.tintColor = UIColor.white
pickerBgView.addSubview(toolbar)
pickerBgView.addSubview(pickerView)
toolbar.setItems([doneButton,space,cancelButton], animated: true)
imagePicker.delegate = self
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.addressRecord.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.addressRecord[row]
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
uploadImageMethod()
}
}
func uploadImageMethod() {
let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Now! Choose an option!", preferredStyle: .actionSheet)
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
//Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
//Create and add first option action
let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .default) { action -> Void in
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .camera
self.imagePicker.delegate = self
self.imagePicker.cameraCaptureMode = .photo
self.present(self.imagePicker, animated: true, completion: {})
} else {
print("Rear camera doesn't exist.")
}
} else if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
self.imagePicker.sourceType = .photoLibrary
self.imagePicker.delegate = self
self.present(self.imagePicker, animated: true, completion: {})
}
}
actionSheetController.addAction(takePictureAction)
//Create and add a second option action
let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose From Camera Roll", style: .default) { action -> Void in
self.imagePicker.sourceType = .photoLibrary
self.imagePicker.delegate = self
self.present(self.imagePicker, animated: true, completion: {})
}
actionSheetController.addAction(choosePictureAction)
//Present the AlertController
self.present(actionSheetController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("select below")
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
//imagePost.image = image //updated
// image1.image = image
print("picked")
print(image)
} else{
print("Something went wrong")
}
self.dismiss(animated: true, completion: nil)
}
}
Error:
Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x12140acc0) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices
One of the two will be used. Which one is undefined.
[Generic] Creating an image format with an unknown type is an error

How to save only UIImageView not the whole screen in my photo app. In Swift

My app has a camera section. It takes a photo and then puts a watermark on the photo. However when the photo is saved, the whole screen is saved, not just the UIImageView. I just want the UIImageView to be saved. It's not that but because the menu bar at the button is not that big. I just think it would look better without the menu bar in the picture.
Photo of app just before taking photo:
Photo of how the picture taken is saved:
This is my code below.
import UIKit
class Camera: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var cameraScreen: UIImageView!
var screenView: UIImageView!
#IBAction func Camera(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)}}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject: AnyObject]!){
cameraScreen.image = image
self.dismiss(animated: true, completion: nil);
screenView = UIImageView()
screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
let text = "Java"
let label = UILabel(frame: CGRect(x: 125, y: 400, width: self.view.frame.width, height: 300))
label.font = UIFont(name: label.font.fontName, size: 200)
label.textColor = UIColor.blue
label.alpha = 0.3
label.text = text
self.view.addSubview(screenView)
self.view.addSubview(label)
// i tried self, nil, nil
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true)
let photo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(photo!, nil, nil, nil)
}
#IBAction func Save(_ sender: AnyObject) {
let alert = UIAlertController(title: "Image Saved", message: "", preferredStyle: .alert)
let okay = UIAlertAction(title: "OK.", style: .default, handler: nil)
alert.addAction(okay)
present(alert, animated: true, completion: nil)
}
}

Trying to save UiimageView but code is saving all of the page. In swift

These 5 lines of code are saving the photo but they are saving the whole screen. Basically the save button is acting as a screen on a laptop. I have a uiimageView outlet that is where the imagepicker displays the photo. I just want uimmmageview to be saved and not the whole page.
My outlets name is cameraScreen. I have tried to insert in the code but it does not work. My app takes a photo and then puts a graphic on it as well.
Here is the code
import UIKit
class Camera: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var cameraScreen: UIImageView!
var screenView: UIImageView!
#IBAction func Camera(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)}}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject: AnyObject]!){
cameraScreen.image = image
self.dismiss(animated: true, completion: nil);
screenView = UIImageView()
screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
let text = "Java"
let label = UILabel(frame: CGRect(x: 125, y: 400, width: self.view.frame.width, height: 300))
label.font = UIFont(name: label.font.fontName, size: 200)
label.textColor = UIColor.blue
label.alpha = 0.3
label.text = text
self.view.addSubview(screenView)
self.view.addSubview(label)
}
#IBAction func Save(_ sender: AnyObject) {
let alert = UIAlertController(title: "Image Saved", message: "", preferredStyle: .alert)
let okay = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okay)
present(alert, animated: true, completion: nil)
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let photo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(photo!, nil, nil, nil)
}}

Choose different images in one View with UIImagePickerController [duplicate]

This question already has an answer here:
Picking two different images in the same view controller using imagePickerController in Swift
(1 answer)
Closed 7 years ago.
We have the following view:
All code is running well but when I finally select a picture , the photo is placed just in one ImageView. It should works like this:
We click each button below the UIImageView and it puts the selected picture in his ImageView.
My problem now is that all buttons are placing the photo in the first UIImageView.
How to place 4 different photos?
class selectorDeFotosViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
//Outlets
#IBOutlet weak var fotoUno: UIImageView!
#IBOutlet weak var fotoDos: UIImageView!
#IBOutlet weak var fotoTres: UIImageView!
#IBOutlet weak var fotoCuatro: UIImageView!
override func viewDidLoad() {
}
//Actions
#IBAction func CamaraUno(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
#IBAction func camaraDos(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
#IBAction func camaraTres(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
#IBAction func camaraCuatro(sender: AnyObject) {
let alertPictureFrom = UIAlertController(title: "De dónde sacar la foto?", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
presentViewController(alertPictureFrom, animated: true, completion: nil)
alertPictureFrom.popoverPresentationController?.sourceRect = CGRect(x: 350.0, y: 458.0, width: 1.0, height: 1.0)
alertPictureFrom.popoverPresentationController?.sourceView = self.view
alertPictureFrom.addAction(UIAlertAction(title: "Cámara", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .Camera
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
alertPictureFrom.addAction(UIAlertAction(title: "Galería", style: .Default, handler: {action in
let picker = UIImagePickerController()
picker.sourceType = .PhotoLibrary
picker.delegate = self
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}))
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
fotoUno.image = image
picker.dismissViewControllerAnimated(true, completion: nil)
}
There are many ways to achieve this.
You press button1, and set a BOOL value buttonOne to YES, and you present the picker, you select the image, and to display the image, you simply check is button is selected or not in the method didFinishPickingImage,so:
if(buttonOne)
{
//set the image view 1 image
}
You do the same for all the four image views:
if(buttonOne)
{
//set the image view 1 image
}
if(buttonTwo)
{
//set the image view 2 image
} if(buttonThree)
{
//set the image view 3 image
} if(buttonFour)
{
//set the image view 4 image
}
Make sure you set the other 3 bool values to NO, when you set one value to YES.

Resources