Nsimage to Nsdata as Png Swift

NSImage to NSData as PNG Swift

You can use the NSImage property TIFFRepresentation to convert your NSImage to NSData:

let imageData = yourImage.TIFFRepresentation

If you need to save your image data to a PNG file you can use NSBitmapImageRep(data:) and representationUsingType to create an extension to help you convert Data to PNG format:

Update: Xcode 11 • Swift 5.1

extension NSBitmapImageRep {
var png: Data? { representation(using: .png, properties: [:]) }
}
extension Data {
var bitmap: NSBitmapImageRep? { NSBitmapImageRep(data: self) }
}
extension NSImage {
var png: Data? { tiffRepresentation?.bitmap?.png }
}

usage

let picture = NSImage(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!)!

let imageURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!.appendingPathComponent("image.png")
if let png = picture.png {
do {
try png.write(to: imageURL)
print("PNG image saved")
} catch {
print(error)
}
}

NSImage to NSData, then to UIImage

OS X:

Instead of using NSKeyedArchiver to convert an NSImage to NSData, use NSImage's TIFFRepresentation method:

NSData *imageData = [self.someImage TIFFRepresentation];
// save imageData to file

iOS:

Read the image data from the file, then convert it to a UIImage using UIImage's +imageWithData: convenience constructor:

NSData *imageData = ...; // load imageData from file
UIImage *image = [UIImage imageWithData: imageData];

UIImage to NSData for Core Data in Swift 3.0

Try this:

if let img = UIImage(named: "hallo.png") {
let data = UIImagePNGRepresentation(img) as NSData?
}

creating an NSImage from downloaded NSData in Swift

avatarData is an NSData, NSImage has a constructor that takes an NSData, just use that:

let image = NSImage(data:avatarData!)

Saving NSImage in Different Formats Locally

You can create a custom method to allow you to specify any image type and also the directory where you would like to save your NSImage. You can also set a default value to the destination directory as the current directory, so if you don't pass the directory url it will save to the current one:

extension NSImage {
func save(as fileName: String, fileType: NSBitmapImageRep.FileType = .jpeg, at directory: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)) -> Bool {
guard let tiffRepresentation = tiffRepresentation, directory.isDirectory, !fileName.isEmpty else { return false }
do {
try NSBitmapImageRep(data: tiffRepresentation)?
.representation(using: fileType, properties: [:])?
.write(to: directory.appendingPathComponent(fileName).appendingPathExtension(fileType.pathExtension))
return true
} catch {
print(error)
return false
}
}
}

You will need also to make sure the url passed to your method is a directory url. You can use URL resourceValues method to get the url isDirectoryKey value and check if it is true:

extension URL {
var isDirectory: Bool {
return (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
}
}

You can also extend NSBitmapImageRep.FileType to provide the associated file path extension:

extension NSBitmapImageRep.FileType {
var pathExtension: String {
switch self {
case .bmp:
return "bmp"
case .gif:
return "gif"
case .jpeg:
return "jpg"
case .jpeg2000:
return "jp2"
case .png:
return "png"
case .tiff:
return "tif"
}
}
}

Playground Testing:

let desktopDirectory = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
// lets change the current directory to the desktop directory
FileManager.default.changeCurrentDirectoryPath(desktopDirectory.path)

// get your nsimage
let picture = NSImage(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!)!

// this will save to the current directory
if picture.save(as: "profile") {
print("file saved as profile.jpg which is the default type")
}
if picture.save(as: "profile", fileType: .png) {
print("file saved as profile.png")
}
if picture.save(as: "profile", fileType: .tiff) {
print("file saved as profile.tif")
}
if picture.save(as: "profile", fileType: .gif) {
print("file saved as profile.gif")
}
if picture.save(as: "profile", fileType: .jpeg2000) {
print("file saved as profile.jp2")
}

// you can also chose a choose another directory without the need to change the current directory
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
if picture.save(as: "profile", at: url) {
print("file saved as profile.jpg at documentDirectory")
}

Convert UIImage to NSData and convert back to UIImage in Swift?

UIImage(data:imageData,scale:1.0) presuming the image's scale is 1.

In swift 4.2, use below code for get Data().

image.pngData()

convert UIImage to NSData and back to UIImage

To convert UIImage to NSData, use either UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality) or UIImagePNGRepresentation(UIImage *image)

To convert NSData to UIImage, use [UIImage imageWithData:imageData]

So your example could look like this:

cell.textLabel.text = [[offlineImageListArray objectAtIndex:indexPath.row] imageName];
UIImage *thumbnail = [self retrieveImageFromDevice:[[offlineImageListArray objectAtIndex:indexPath.row] imageName]];
NSData* data = UIImagePNGRepresentation(thumbnail);
ImageData *imageDataObject = [[ImageData alloc] initWithImageId:[[offlineImageListArray objectAtIndex:indexPath.row]imageId] imageName:[[offlineImageListArray objectAtIndex:indexPath.row] imageName] imageData:data];
[imagesArray addObject:imageDataObject];

References: https://developer.apple.com/LIBRARY/IOS/documentation/UIKit/Reference/UIKitFunctionReference/Reference/reference.html
https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIImage_Class/Reference/Reference.html

get PNG representation of NSImage in swift

The documentation says:

func representationUsingType(_ storageType: NSBitmapImageFileType,
properties properties: [NSObject : AnyObject]) -> NSData?

So it expects a dictionary, not a nil value. Supply an empty dict like this:

var pngCoverImage = bitmap!.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])

Only if an Optional is specified (that is it where [NSObject : AnyObject]?) you could pass a nil value.



Related Topics



Leave a reply



Submit