I have a UIImage variable, a. I would like to use it within my app as a .png data file. How do I go about recasting a back into a UIImage for use?
How can I cast this data object back into a UIImage?
let pngImage = a!.pngData()
Converting UIImage to PNG Data:
extension UIImage {
// UIImage to Data (PNG Representation)
var PNGData: Data? {
return UIImagePNGRepresentation(self)
}
}
Using your example:
let a = UIImage("foo") // Sample image named foo
UIImage to Data:
let pngData = a.data
Data to UIImage:
let pngImage = UIImage(data: pngData)
Related
When the user selects an item from their photo library, the app saves the UIImage to the app's directory using the following code:
let imageUUID = UUID()
let filename = getDocumentsDirectory().appendingPathComponent("\(imageUUID)")
guard let uiImage = newImage else { return}
if let jpegData = uiImage.jpegData(compressionQuality: 0.8) {
try? jpegData.write(to: filename, options: [.atomicWrite, .completeFileProtection])
}
How can I use the saved image in a view?
Thanks!
First, you should save the UUID somewhere so that you can read the file later. This could be in UserDefaults, a JSON file, CoreData, or whatever, depending on your needs.
Suppose you have the path to the file stored in filePath, you can create an Image like this:
Image(uiImage: UIImage(contentsOfFile: filePath) ?? UIImage())
This will use an empty image as fallback if it failed to read the file.
Following code convert UIImage to Image in SwiftUI:
let uiImage = UIImage(contentsOfFile: path) ?? UIImage() // Access it from your storage
let image = Image(uiImage: uiImage)
There are different UIImage initializer methods available, you can use any one of them to get UIImage instance.
https://developer.apple.com/documentation/swiftui/image
You will like this tutorial of Coredata with SwiftUI: https://www.raywenderlich.com/9335365-core-data-with-swiftui-tutorial-getting-started
I have converted my images with this codes below and this will return base64 of my images but the problem is that when I upload them into the server I just see the white image - can you suggest me the better way to convert images to base64 or this is the best way that I choose
here is the converting image to base64
func base64(from image: UIImage) -> String? {
UIGraphicsBeginImageContext(image.size)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageData = UIImageJPEGRepresentation(image!, 1.0)
if let imageString = imageData?.base64EncodedString(options: .endLineWithLineFeed) {
return imageString
}
return nil
}
Try this method:
func convertImageToBase64(_ image:UIImage) -> String
{
let imageData = UIImageJPEGRepresentation(image, 1)//get imageData from image
if(imageData != nil)
{
let Strbase64 = imageData?.base64EncodedString(options: .endLineWithCarriageReturn)//encode imageData
return Strbase64!//return encoded string
}
return ""
}
You passed a UIImage to this method, but never did anything with it, but rather created a new UIImage using UIGraphicsGetImageFromCurrentImageContext, but you never drew anything to that context. That's why the resulting images are white.
But you don't need those UIGraphics calls at all. Just grab the JPEG representation of the UIImage that you passed into this method, and convert it to a base 64 encoded string:
func convertImageToBase64(_ image: UIImage) -> String? {
return UIImageJPEGRepresentation(image, 1)?.base64EncodedString()
}
It is white because nothing is drawn on current context !!!
You are just UIGraphicsBeginImageContext with size
and get with UIGraphicsGetImageFromCurrentImageContext
it will always gives you a white image and there is no relation with Base64
If you want to render something then use like below
yourImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
and after that fetch image from currentContext
EDIT
func base64(from image: UIImage) -> String? {
UIGraphicsBeginImageContext(image.size)
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageData = UIImageJPEGRepresentation(image!, 1.0)
if let imageString = imageData?.base64EncodedString(options: .endLineWithLineFeed) {
return imageString
}
return nil
}
First check wether the error you are facing is from your app or server side .You can choose online base64 to image converter .Copy your base64 String and check them first , you can choose this link
https://codebeautify.org/base64-to-image-converter
I am trying to convert WKImage to Data(NSData) but always getting nil.
let image = WKImage(imageName: "sample")
print("Image = \(image)")
let imageData = image.imageData
print("Image Data = \(imageData)")
Below is out put
Image = <WKImage: 0x7a66ff40>
Image Data = nil
If you are creating WKImage with init(imageName: String) constructor, only imageName parameter will not be nil. image and imageData parameters are not nil only when WKImage was created via init(image: UIImage) or init(imageData: Data) respectfully.
You can get this imageName, then create UIImage with it's init(named: String) constructor, and then convert this UIImage to data using UIImageJPEGRepresentation or UIImagePNGRepresentation functions:
UIImagePNGRepresentation(UIImage(named: image.imageName!)!)
I have to populate table cell from database and images are on device.
I've to store that image in imageDataObject, how to convert that UIImage to NSData.
Please suggest, I tried many solution but it's not converting back that NSData to UIImage.
cell.textLabel.text = [[offlineImageListArray objectAtIndex:indexPath.row] imageName];
UIImage *thumbnail = [self retrieveImageFromDevice:[[offlineImageListArray objectAtIndex:indexPath.row] imageName]];
NSData* data = ??????????;
ImageData *imageDataObject = [[ImageData alloc] initWithImageId:[[offlineImageListArray objectAtIndex:indexPath.row]imageId]
imageName:[[offlineImageListArray objectAtIndex:indexPath.row] imageName] imageData:data];
[imagesArray addObject:imageDataObject];
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
Try With this:
Use this for convert UIImage to NSData.
NSData *imagedata = UIImagePNGRepresentation(thumbnail);
Try this for image data convert back to UIImage
UIImage *image= [UIImage imageWithData:imagedata];
in Swift version:
let imageData = image!.pngData()
let imageFromData = UIImage(data: imageData)
See: https://developer.apple.com/documentation/uikit/uiimage/1624096-pngdata
Use if-let block with Data to prevent app crash & safe execution of code, as function UIImagePNGRepresentation returns an optional value.
if let img = UIImage(named: "TestImage.png") {
if let data:Data = UIImagePNGRepresentation(img) {
// Handle operations with data here...
}
}
Note: Data is Swift 3 class. Use Data instead of NSData with
Swift 3
Generic image operations (like png & jpg both):
if let img = UIImage(named: "TestImage.png") { //UIImage(named: "TestImage.jpg")
if let data:Data = UIImagePNGRepresentation(img) {
handleOperationWithData(data: data)
} else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}
By using extension:
extension UIImage {
var pngRepresentationData: Data? {
return UIImagePNGRepresentation(img)
}
var jpegRepresentationData: Data? {
return UIImageJPEGRepresentation(self, 1.0)
}
}
*******
if let img = UIImage(named: "TestImage.png") { //UIImage(named: "TestImage.jpg")
if let data = img.pngRepresentationData {
handleOperationWithData(data: data)
} else if let data = img.jpegRepresentationData {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}
Convert Data from Image:
Try JPEG or PNG representation depending on your image format:
UIImageJPEGRepresentation
Returns the data for the specified image in JPEG format.
NSData * UIImageJPEGRepresentation (
UIImage *image,
CGFloat compressionQuality
);
UIImagePNGRepresentation
Returns the data for the specified image in PNG format
NSData * UIImagePNGRepresentation (
UIImage *image
);
Example:
extension UIImage {
var pngRepresentationData: Data? {
return UIImagePNGRepresentation(img)
}
var jpegRepresentationData: Data? {
return UIImageJPEGRepresentation(self, 1.0)
}
}
Use:
let data = myImage.jpegRepresentationData
let data1 = myImage.pngRepresentationData
Convert Image from Data:
let image = UIImage(data: data)
I am trying to load UIImage object from NSData, and the sample code was to NSImage, I guess they should be the same. But just now loading the image, I am wondering what's the best to troubleshoot the UIImage loading NSData issue.
I didn't try UIImageJPEGRepresentation() before, but UIImagePNGRepresentation works fine for me, and conversion between NSData and UIImage is dead simple:
NSData *imageData = UIImagePNGRepresentation(image);
UIImage *image=[UIImage imageWithData:imageData];
UIImage has an -initWithData: method. From the docs: "The data in the data parameter must be formatted to match the file format of one of the system’s supported image types."
Try this to convert an image to NSdata:
UIImage *img = [UIImage imageNamed:#"image.png"];
NSData *data1 = UIImagePNGRepresentation(img);
theData should be a NSData object which already contains the data. You need to do the file loading/downloading to the NSData object before it is used. You can inspect it by using NSLog on theData and see if it contains the valid data.
For safe execution of code, use if-let block with Data, as function UIImagePNGRepresentation returns, optional value.
if let img = UIImage(named: "Hello.png") {
if let data:Data = UIImagePNGRepresentation(img) {
// Handle operations with data here...
}
}
Note: Data is Swift 3 class. Use Data instead of NSData with
Swift 3
Generic image operations (like png & jpg both):
if let img = UIImage(named: "Hello.png") {
if let data:Data = UIImagePNGRepresentation(img) {
handleOperationWithData(data: data)
} else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}
By using extension:
extension UIImage {
var pngRepresentationData: Data? {
return UIImagePNGRepresentation(img)
}
var jpegRepresentationData: Data? {
return UIImageJPEGRepresentation(self, 1.0)
}
}
*******
if let img = UIImage(named: "Hello.png") {
if let data = img.pngRepresentationData {
handleOperationWithData(data: data)
} else if let data = jpegRepresentationData {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}