I'm building an app that allows you to upload images from your library to the server. This server is used as essentially an image repository. For this reason, it's absolutely necessary to store it in it's original image format: Either JPG, PNG, or GIF. I.E. If the PNG image has transparency, that HAS to be preserved, it cannot simply be converted to a JPG.
I USED to get the image format using UIImagePickerControllerReferenceURL:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let selectedImage = info[UIImagePickerControllerEditedImage] as! UIImage
let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
if (assetPath.absoluteString?.hasSuffix("JPG"))! {
print("JPG")
}
else if (assetPath.absoluteString?.hasSuffix("PNG"))! {
print("PNG")
}
else if (assetPath.absoluteString?.hasSuffix("GIF"))! {
print("GIF")
}
else {
print("Unknown")
}
self.dismiss(animated: true, completion: nil)
self.showImageFieldModal(selectedImage: selectedImage)
}
But UIImagePickerControllerReferenceURL has been deprecated in iOS11. It suggests using UIImagePickerControllerPHAsset, but that's not a URL. I'm not sure what I'm supposed to do with that as a PHAsset object...
In iOS11 you can use the original image url key UIImagePickerControllerImageURL and use URL resourceValues method to get its typeIdentifierKey:
if #available(iOS 11.0, *) {
if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
print(imageURL.typeIdentifier ?? "unknown UTI") // this will print public.jpeg or another file UTI
}
} else {
// Fallback on earlier versions
}
You can use the typeIdentifier extension from this answer to find out the fileURL type identifier:
extension URL {
var typeIdentifier: String? {
return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
}
}
Related
What do I simply do?
let pasteboard = UIPasteboard.general
let base64EncodedImageString = "here_base_64_string_image"
let data = Data(base64Encoded: base64EncodedImageString)
let url = data?.write(withName: "image.jpeg")
pasteboard.image = UIImage(url: url) //and now when I try to paste somewhere that image for example in imessage, it is rotated... why?
What may be important:
It happens only for images created by camera.
However, if use exactly the same process (!) to create activityItems for UIActivityViewController and try to use iMessage app, then it works... why? What makes the difference?
I use above two simple extensions for UIImage and Data:
extension Data {
func write(withName name: String) -> URL {
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name)
do {
try write(to: url, options: NSData.WritingOptions.atomic)
return url
} catch {
return url
}
}
}
extension UIImage {
convenience init?(url: URL?) {
guard let url = url else {
return nil
}
do {
self.init(data: try Data(contentsOf: url))
} catch {
return nil
}
}
}
Before server returns base64EncodedString I upload an image from camera like this:
func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
let image = info[.originalImage] as? UIImage
let encodedBase64 = image?.jpegData(compressionQuality: 0.9)?.base64EncodedString() ?? ""
//upload encodedBase64 to the server... that is all
}
I am not sure but I think UIPasteBoard converts your image to PNG and discards its orientation. You can explicitly tell the kind of data you are adding to the pasteboard but I am not sure if this would work for your scenery.
extension Data {
var image: UIImage? { UIImage(data: self) }
}
setting your pasteboard data
UIPasteboard.general.setData(jpegData, forPasteboardType: "public.jpeg")
loading the data from pasteboard
if let pbImage = UIPasteboard.general.data(forPasteboardType: "public.jpeg")?.image {
}
Or Redrawing your image before setting your pasteboard image property
extension UIImage {
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()
}
}
UIPasteboard.general.image = image.flattened()
I am using UIImagePickerController to use my camera like so:
#objc func toggle() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
//Define UIImagePickerController variable
let imagePicker = UIImagePickerController()
//Assign the delegate
imagePicker.delegate = self
//Set image picker source type
imagePicker.sourceType = .camera
//Allow Photo Editing
imagePicker.allowsEditing = true
//Present camera
UIApplication.topViewController()?.present(imagePicker, animated: true, completion: nil)
}
}
Now I am trying to capture the image taken using the didFinishPickingMediaWithInfo method, I got this example online:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let imageUrl = info[UIImagePickerControllerOriginalImage] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
UIApplication.topViewController()?.dismiss(animated: true, completion: nil);
}
But I changed UIImagePickerControllerReferenceURL to UIImagePickerControllerOriginalImage as UIImagePickerControllerReferenceURL is nil. but after I change that I get this fatal error:
Could not cast value of type 'UIImage' (0x1b6b02b58) to 'NSURL'
How do I save the image take from the camera? What am I doing wrong?
Write your code as following this will give you image.
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
UIImagePickerControllerOriginalImage return image not NSURL
Write following code to get image url in iOS 11. From iOS 11 UIImagePickerControllerImageURL is available, earlier there are UIImagePickerControllerMediaURL key to get image url.
if #available(iOS 11.0, *) {
if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
print(imageURL)
}
} else {
if let imageUrl = info[UIImagePickerControllerMediaURL] as? URL {
print(imageUrl)
}
}
I hope this will help you.
The one who are searching for complete method to implement for Swift 4.2+
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
imageView.image = pickedImage
}
imgPicker.dismiss(animated: true, completion: nil)
}
This will return you the original image according to new syntax
For Image URL and Media URL, Use the respective
let imgURL = info[UIImagePickerController.InfoKey.imageURL]
let mediaURL = info[UIImagePickerController.InfoKey.mediaURL]
hi I want to convert images into Data but the problem is that the Data will return nil
I want to upload images with Alamofire so I need to convert images before using Alamofire upload here is my codes
let imageData = UIImageJPEGRepresentation(ViewController.imageUpload[i], 1.0)
Alamofire.upload(imageData! , to: "http://example.com/api/file?api_token=\(api_token)&id=\(postID)").responseJSON { response in
debugPrint(response)
}
Try below code to get imageData and make sure you are passing right image there not nil,
For PNG:-
let data = UIImagePNGRepresentation(ViewController.imageUpload[i]) as NSData?
For JPEG:-
let data = UIImageJPEGRepresentation(ViewController.imageUpload[i], 1.0) as NSData?
And also check which image extension you are using while saving (PNG or JPEG)
To know the image extension, please have a look into below code,
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if (!(picker.sourceType == UIImagePickerControllerSourceType.Camera)) {
let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
if assetPath.absoluteString.hasSuffix("JPG") {
}
}
}
I would like to save the URL of the photos have been taken from the camera or exinting in the camera roll and have been selected.
Your question is extremely vague with nothing for us to work with. But in any case, I just created an app requiring that logic so I would just share with you
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// Clear data if picture is repicked
imageLocalURL = nil
imageData = nil
imageSelected = info[UIImagePickerControllerOriginalImage] as? UIImage
if info[UIImagePickerControllerReferenceURL] != nil {
// This would mean that image is chosen from photo library
referenceURL = info[UIImagePickerControllerReferenceURL] as? NSURL
let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceURL! as NSURL], options: nil)
let asset = assets.firstObject
asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (contentEditingInput, info) in
// This would be the URL of your image in photo library
self.imageLocalURL = contentEditingInput?.fullSizeImageURL
} else {
// This means that image is taken from camera
imageData = UIImageJPEGRepresentation(imageSelected!, 1.0)
}
dismissViewControllerAnimated(true, completion: nil)
}
I surely hope I am missing something because I do not understand why this is working the way it does. I have a PNG Image, which has a fully transparent background because I want to overlay it on other images inside a UIImageView.
PNG images included in the XCode project all work fine as they should. The problem is when I select these same PNG images on the fly using UIImagePickerController and then assigning it to the UIImageView, for some really bizarre reason, it is not respecting it as a PNG Image with transparency and instead it adding a white background.
Anyone seen this before and how do I get around this?
* UPDATE #1: I decided to try something that seems to confirm my theory. I decided to email myself the original PNG images I saved to my device and lo and behold, the images came to me as JPG. Seems to me that when you save an image to Photos on iPhone it converts it to JPG, this is rather shocking to me. Hope someone has a way around this. The original images testImage1.png and testImage2.png saved to Photos and then emailed back to myself, returned as IMG_XXXX.jpg and IMG_XXXX.jpg
* UPDATE #2: I kept playing around we this more and found out a few things and in the process was able to answer my own question. (1) My theory in UPDATE #1 is partially correct, but the conversion does not happen when saving the Photo, seems like it is on the fly. Internally photos stores the original image extension (2) I was able to validate this when I realized in my UIImagePickerControllerDelegate that I was using
let imageData = UIImageJPEGRepresentation(image, 1.0)
instead of this
let imageData = UIImagePNGRepresentation(image)
When I used the second line of code, it was recognizing the original transparency properties for the image.
Yes, the call to UIImageJPEGRepresentation will convert the resulting image into a JPEG, which doesn't support transparency.
BTW, if your intent is to get the NSData for the image for other reasons (e.g. uploading to server, emailing, etc.), I would recommend against both UIImageJPEGRepresentation and UIImagePNGRepresentation. They lose meta data, can make the asset larger, if suffer some image degradation if you use quality factor of less than 1, etc.
Instead, I'd recommend going back and get the original asset from the Photos framework. Thus, in Swift 3:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let url = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
if let asset = result.firstObject {
let manager = PHImageManager.default()
manager.requestImageData(for: asset, options: nil) { imageData, dataUTI, orientation, info in
if let fileURL = info!["PHImageFileURLKey"] as? URL {
let filename = fileURL.lastPathComponent
// use filename here
}
// use imageData here
}
}
}
picker.dismiss(animated: true)
}
If you have to support iOS 7, too, you'd use the equivalent ALAssetsLibrary API, but the idea is the same: Get the original asset rather than round-tripping it through a UIImage.
(For Swift 2 rendition, see previous revision of this answer.)
Swift 3 version of answer by #Rob
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let URL = info[UIImagePickerControllerReferenceURL] as? NSURL {
let result = PHAsset.fetchAssets(withALAssetURLs: [URL as URL], options: nil)
if let asset:PHAsset = result.firstObject! as PHAsset {
let manager = PHImageManager.default()
manager.requestImageData(for: asset, options: nil) { imageData, dataUTI, orientation, info in
let fileURL = info!["PHImageFileURLKey"] as? NSURL
let filename = fileURL?.lastPathComponent;
// use imageData here
}
}
}
picker.dismiss(animated: true, completion: nil)
}
An alternative solution uses the PHAssetResourceManager rather than PHImageManager. Using Xcode 10, Swift 4.2.
func imageFromResourceData(phAsset:PHAsset) {
let assetResources = PHAssetResource.assetResources(for: phAsset)
for resource in assetResources {
if resource.type == PHAssetResourceType.photo {
var imageData = Data()
let options = PHAssetResourceRequestOptions()
options.isNetworkAccessAllowed = true
let _ = PHAssetResourceManager.default().requestData(for: resource, options: options, dataReceivedHandler: { (data:Data) in
imageData.append(data)
}, completionHandler: { (error:Error?) in
if error == nil, let picked = UIImage(data: imageData) {
self.handlePickedImage(picked: picked)
}
})
}
}
}
Use it like this:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true)
let mediaType = info[UIImagePickerController.InfoKey.mediaType] as! NSString
if mediaType == kUTTypeImage || mediaType == kUTTypeLivePhoto {
if #available(iOS 11.0, *) {
if let phAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
self.imageFromResourceData(phAsset: phAsset)
}
else {
if let picked = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage) {
self.handlePickedImage(picked: picked)
}
}
}
else if let picked = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage) {
self.handlePickedImage(picked: picked)
}
}
}