You are trying to convert the UIImage
object to the NSUserDefaults
type in order to save it to NSUserDefaults
.
Use the UIImagePNGRepresentation
or UIImageJPEGRepresentation
methods to
I understand that PNG and JPEG images can be converted to NSData
types, but I would like to know how to convert them to NSData
types without specifying PNG or JPEG, such as unknown format of the original image.
NSKeyedArchiver.archivedDataWithRootObject
I tried converting the UIImage
(generated from the filename) but it doesn't seem to archive correctly.
Thank you for your cooperation.
swift xcode uiimage uikit
Use UIImagePNGRepresentation() when UIImage is in PNG format and UIImageJPEGRepresentation() when you are in JPEG format.You don't have to worry about the original image format.
Specifically, it looks like this.
(Verified by Xcode 7.0.1)
//UIIimage in some way
let image = UIImage (named: "pic01")!
// Convert to NSData as PNG format image format
iflet data=UIImagePNGRepresentation(image){
// save data
}
By the way, saving UIImage to NSUserDefaults is not recommended.
Why can't UIImage
be saved using NSKeyedArchiver
?So, there's an answer to the reference, but
A UIImage object is a high-level way to display image data.You can create images from files, from Quartz image objects, or from raw image data you receive.The UIImage class also offers special options for drawing images to the current graphics and present conditions Whatever the format of the original image is, if you are viewing it on your display, it is stored in memory as a collection of pixels. To access this pixel data, you can get In addition, UIImage
is not an image itself, but a class that provides a means for dealing with image objects and bitmaps handled by Quartz
.CGImage
and use CGDataProvider
, but storing it as it is is a waste of space and is not common (Windows Bitmap is also compressed continuously).UIImagePNGRepresentation()
and others will compress the pixel data managed by UIImage
, but these are not methods, but functions provided by UIKit
© 2024 OneMinuteCode. All rights reserved.