Converting an Image to Data and Vice Versa [closed] - image

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am using swift in Xcode and I need to convert an image to data in order to save it in SQLite db and also to convert the data object back to an image when I retrieve it from the database.
Any help please?
Simon

Swift 5.1 or later
To convert from UIImage to Data you can use UIImagePNGRepresentation or UIImageJPEGRepresentation if you need to reduce the file size.
extension UIImage {
var jpeg: Data? { jpegData(compressionQuality: 1) } // QUALITY min = 0 / max = 1
var png: Data? { pngData() }
}
To convert back to Image from Data you just need to use UIImage(data:) initializer:
extension Data {
var uiImage: UIImage? { UIImage(data: self) }
}
Playground
let image = UIImage(data: try! Data(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!))!
if let jpegData = image.jpeg {
print(jpegData.count) // 416318 number of bytes contained by the data object
if let imageFromData = jpegData.image {
print(imageFromData.size) // (719.0, 808.0)
}
}
if let pngData = image.png {
print(pngData.count) // 1282319
if let imageFromData = pngData.image {
print(imageFromData.size) // (719.0, 808.0)
}
}

Related

how to create a property that counts every letter in every word in an array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I have a #State private var usedWords = String
this array store the history of words that are used in the game
I have a property that counts the letters of every single letter in each word from the above array by using .count
I want to create a new variable that counts every letter in all the words in the above array
You should look into the array instance method reduce. Example:
let names = ["Jessica", "Nick", "Layla", "Elanor"]
let count = names.reduce(0) { $0 + $1.count }
You can do the following:
usedWords.joined(separator: "").count
Complete example:
struct SomeView: View {
#State var usedWords = [String]()
var body: some View {
VStack {
Text("\(usedWords.joined(separator: "").count)")
Button {
let words = ["Swift", "Objective C", "Kotlin", "Java", "Javascript", "Dart"]
usedWords.append(words[Int.random(in: 0..<words.count)])
} label: {
Text("Add Word")
}
}
}
}
If you have state property your solution mb like this:
struct SomeView: View {
#State var usedWords = [String]()
var lettersCount: Int {
usedWords.reduce(0) { $0 + $1.count }
}
...
}
Every change of usedWords property will trigger view redraw and recalculation of lettersCount computed property, thats why view will always use actual value of lettersCount.
Letters counting was used from JLM answer.

Native framework for copying file on macOS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Is there a framework in macOS that I can use to programmatically copy files and get a progress bar the same as copying files from Finder?
Alternatively, I can do the copy using cp or filesystem APIs and use NSProgressIndicator to implement the progress bar.
You can use copyFile.
Here is example of copyfile with Progress Callback.
I had the same problem, but I needed it in swift.
But great Project Parag it really help me!
Thats my Copy Function.
func createCopy(of:URL, to:URL,skip:Bool) throws {
if !skip {
if FileManager.default.fileExists(atPath: to.path) {
print("\n\n did not copy \n\(of.lastPathComponent.utf8CString) \nto \n\(to.path)\n\n")
return
}
}
//open window
let copyStoryboard = NSStoryboard.init(name: "copyProgessWindow", bundle: nil)
self.progressWindowConrtoller = copyStoryboard.instantiateController(withIdentifier: "CopyProgressWindow") as! NSWindowController
let application = NSApplication.shared
//set Up view
let viewController = self.progressWindowConrtoller!.contentViewController as! CopyViewController
viewController.path_copyFrom.url = of
viewController.path_copyTo.url = to
DispatchQueue.global(qos: .userInteractive).async{
do{
let bufferSize:Int = 64*1024;
var buffer = [Int32](repeating: 0, count: Int(bufferSize))
let open_source = open(of.path, O_RDONLY);
let open_target = open(to.path, O_RDWR | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR);
let attrSource = try FileManager.default.attributesOfItem(atPath: of.path)
let sourceFileSize = attrSource[FileAttributeKey.size] as! UInt64
var bytes_read = 0;
bytes_read = read(open_source, &buffer, bufferSize);
while(bytes_read > 0){
write(open_target, &buffer, bufferSize);
if FileManager.default.fileExists(atPath: to.path) {
let attrTarget = try FileManager.default.attributesOfItem(atPath: to.path)
let targetFileSize = attrTarget[FileAttributeKey.size] as! UInt64
DispatchQueue.main.async {
viewController.progressbar_progBar.doubleValue = self.progressProcent
}
self.progressProcent = Double(targetFileSize)/Double(sourceFileSize)
print(self.progressProcent)
}
bytes_read = read(open_source, &buffer, bufferSize);
}
// copy is done, or an error occurred
close(open_source);
close(open_target);
sleep(2)
DispatchQueue.main.async {
application.abortModal()
self.progressWindowConrtoller!.close()
}
}
catch{
print(error)
}
}
application.runModal(for: self.progressWindowConrtoller!.window!)
}
I have a storyboard file called 'copyProgessWindow.storyboard' and important is the storyboardID set to 'CopyProgressWindow'. and it looks like this:
storyboardCopyProgress
Thats my ViewController for the view you see:
class CopyViewController: NSViewController {
#IBOutlet weak var path_copyFrom: NSPathControl!
#IBOutlet weak var path_copyTo: NSPathControl!
#IBOutlet weak var label_remaindingTime: NSTextField!
#IBOutlet weak var progressbar_progBar: NSProgressIndicator!
override func viewDidLoad() {
super.viewDidLoad()
}
}

Load an image from a Base64-encoded string [duplicate]

This question already has answers here:
Decode Base-64 encoded PNG in an NSString
(6 answers)
Closed 5 years ago.
So I have an empty image view inside a .xib file. And there is another .m file that is a string but there an image loaded inside of it. Can someone please explain in detail how to load the image from the string and put it inside the imageview thats in the xib file?
If it's base64 string, you could use this type of website to extract it : http://codebeautify.org/base64-to-image-converter
In swift you could use this code to get the Image:
let dataFromBase64 = NSData(base64EncodedString: yourString, options: NSDataBase64DecodingOptions(rawValue: 0))!
let image = UIImage(data: dataFromBase64)!
yourImageView.image = image
Hope it helps.
Pierre
For Swift 3.
extension String {
public func base64ToImage() -> UIImage? {
if let dataDecoded = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters) {
return UIImage(data: dataDecoded)
}
return nil
}
}
Them you call:
if let image = yourBase64Image.base64ToImage() {
imageView.image = image
}
Hope it helps.

Swift 3 base64 encode image for upload

I have some nice code that allows me to pic and image and then display it in app. I was also uploading the profilePic.image to my database (as a blob) but I realised that this was not actually uploading the image itself but just data about the image so I could not render anything back as there was nothing to decode. So I want to transform this function to get the chosen image and encode it to base64 and utilise same working upload
func imagePickerController(
_ selectImage: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject])
{
let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage //2
// imageByCroppingToRect()
profilePic.contentMode = .scaleAspectFit //3
profilePic.image = chosenImage //4
dismiss(animated: true, completion: nil) //5
}
You have to convert the UIImage to a format your website can read, e.g. jpeg before encoding it in base 64.
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(chosenImage, jpegCompressionQuality)?.base64EncodedString() {
// Upload base64String to your database
}
Note: In iOS 12 UIImageJPEGRepresentation was replaced by an instance method jpegData of UIImage:
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = chosenImage.jpegData(compressionQuality: jpegCompressionQuality)?.base64EncodedString() {
// Upload base64String to your database
}
Refer to the Apple documentation for UIImageJPEGRepresentation and Data
Data has a function to return a base64 representation of itself as another Data. No need to convert to String and back.
Take a look at the docs for Data.base64EncodedData()
if let data = UIImageJPEGRepresentation(photos, 0.5)?.base64EncodedData() {
form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
}

Is it possible to check if a directory is empty in Swift 2.1? [duplicate]

This question already has answers here:
Getting list of files in documents folder
(7 answers)
Closed 7 years ago.
For example I'd like to check if: Users/username/Desktop/folder is empty, or better check if it has files with an .png extension?
I'm really new at all this but if anyone knows please help me :)
Use contentsOfDirectoryAtPath to get the list of all files in a directoly, then filter the array for .png files
let path = "/Users/username/Desktop/folder"
do {
let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
let images = contents.filter { $0.lowercaseString.hasSuffix(".png") }
} catch let error as NSError {
// Directory not exist, no permission, etc.
print(error.localizedDescription)
}
let fileManager = NSFileManager.defaultManager()
let folderPath = "/Users/username/Desktop/folder"
if let contentEnumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath) {
var numFilesWithSuffix = 0
let mySuffix = "png"
while let fileOrFolder = contentEnumerator.nextObject() as? String {
if fileOrFolder.hasSuffix(mySuffix) {
numFilesWithSuffix += 1 // count occurences
}
}
}

Resources