UIImage→ NSData Conversion Questions

Asked 1 years ago, Updated 1 years ago, 90 views

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.archivedDataWithRootObjectI 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

2022-09-29 22:44

2 Answers

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.


2022-09-29 22:44

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

UIImage Class Reference

UIImage is not an image itself, but a class that provides a means for dealing with image objects and bitmaps handled by Quartz.

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 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).

In addition, UIImagePNGRepresentation() and others will compress the pixel data managed by UIImage, but these are not methods, but functions provided by UIKit


2022-09-29 22:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.