简体   繁体   中英

How to create a NSImage from a NSData with Swift

Sorry to ask such a simple but this is my first program in Swift... I try to create a NSImage from a NSData that contains a JPEG image I loaded from disk (URLs are in an array name choseFiles[]).

The compiler issues an error on the second and I'm stuck:'NSData' is not implicitly convertible to 'Data'; did you mean to use 'as' to explicitly convert?

Thank you

let imageAsNSData = NSData(contentsOf: chosenFiles[0])  // UIKit/UIImage for iOS not MacOS !
let imageAsNSImage = NSImage(data: imageAsNSData)
if (imageAsNSImage) {
   // image could be created from NSData
   //

} else {

   // image could NOT be created from NSData
   //

}

----- EDIT -----

I tried

let imageAsNSImage = NSImage(data: imageAsNSData! as Data) if (imageAsNSImage != nil) { which seems to work (at least for the compiler). Am I correct?

You can use swift Data to get your image:

do {
    let imageData = try Data(contentsOf:  chosenFiles[0])
    NSImage(data: imageData)
} catch {
    print("Unable to load data: \(error)")
}

Now in swift3 NSData is replaced by Data. When you are downloading image from url store it as Data not NSData.

imageView.image = NSImage.init(data: data! as Data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM