Convert UIView to .png in Swift
Try this:
UIGraphicsBeginImageContextWithOptions(myView.layer.frame.size, false, scale)
myView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let data = UIImagePNGRepresentation(viewImage)
let documentsDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let writePath = documentsDir.stringByAppendingPathComponent("myimage.png")
data.writeToFile(writePath, atomically:true)
Can't generate PNG file from UIView snapshot
Try the following extension:
extension UIView {
func getImageFromCurrentContext(bounds: CGRect? = nil) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds?.size ?? self.bounds.size, false, 0.0)
self.drawHierarchy(in: bounds ?? self.bounds, afterScreenUpdates: true)
guard let currentImage = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
return currentImage
}
}
Pass the bounds if you would like 1/3 of the view or don't provide a bounds to get the image of the entire view.
Tested with sample code:
import UIKit
class ViewController: UIViewController {
@IBOutlet private(set) var testView: UIView!
@IBOutlet private(set) var testImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.testImageView.image = self.testView.getImageFromCurrentContext()
}
}
}
I made UIView
on the storyboard have a sample label inside it and changed the background color just to verify it is in fact creating the image. Then added an UIImageView
under that. Connected the UIView
to testView
and the UIImageView
to testImageView
.
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()
Create UIImage from shadowed view while retaining alpha?
Try setting your UIImageView
's backgroundColor
to [UIColor clearColor]
- this may enable your current solution to work.
imageView.backgroundColor = [UIColor clearColor];
UIGraphicsBeginImageContext(CGSizeMake(320, 396));
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Source: Converting a CGLayer to a *transparent* UIImage and PNG file in CoreGraphics iphone
How to convert a PNG to a WebP in Swift?
I ended up using another framework to convert PNG to WebP: https://github.com/seanooi/iOS-WebP, had to create the wrapper to use it on swift but it works very good
My wrapper is very simple but does what I needed:
#import <Foundation/Foundation.h>
#import "WebPWrapper.h"
#import "UIImage+WebP.h"
@implementation WebPWrapper
-(NSData *)convertUIImageToWebp:(UIImage *)image :(int)quality {
NSData *webPData = [UIImage imageToWebP:image quality:quality];
return webPData;
}
@end
In swift I use it this way:
let webPData = WebPWrapper().convertUIImage(toWebp: image, 90)
Loading/Downloading image from URL on Swift
Xcode 8 or later • Swift 3 or later
Synchronously:
if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) {
imageView.contentMode = .scaleAspectFit
imageView.image = image
}
Asynchronously:
Create a method with a completion handler to get the image data from your url
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
Create a method to download the image (start the task)
func downloadImage(from url: URL) {
print("Download Started")
getData(from: url) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
// always update the UI from the main thread
DispatchQueue.main.async() { [weak self] in
self?.imageView.image = UIImage(data: data)
}
}
}
Usage:
override func viewDidLoad() {
super.viewDidLoad()
print("Begin of code")
let url = URL(string: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")!
downloadImage(from: url)
print("End of code. The image will continue downloading in the background and it will be loaded when it ends.")
}
Extension:
extension UIImageView {
func downloaded(from url: URL, contentMode mode: ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { [weak self] in
self?.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: ContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
}
}
Usage:
imageView.downloaded(from: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")
Saving UIGraphicsContext image as .png instead of .jpg
Try converting your image's data to a PNG data representation then back into a PNG image, ex:
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
NSData *pngImageData = UIImagePNGRepresentation(smallImage);
UIImage *pngSmallImage = [UIImage imageWithData:pngImageData];
UIImageWriteToSavedPhotosAlbum(pngSmallImage, self, nil, nil); //20kb
UIGraphicsEndImageContext();
Related Topics
How to Add Followed Text to Uitextfield
Circular Button Becomes Rounded Rectangle After Size Increase
Format Currency in Textfield in Swift on Input
Changing Constraint When Keyboard Appears - Swift
How to Read References Given by Ptr_Refs in iOS
Swift Save Viewcontroller State Using Coder Beyond App Close
Uialertcontroller Visible Only When Viewdidappear Has Finished Its Call
How to Position UI Elements on Background Image Relative to the Image
Using Simple Ping in Swift (Ios)
How to Deal with Dynamic Sections and Rows in iOS Uitableview
Scroll All the Way Down to the Bottom of Uitableview
Firebase Connection Manager Should Return Only One Result
iPhone Simulator Plays Video, Real Device Won'T
How to Turn Off Core Data Write-Ahead Logging in Swift Using Options Dictionary
Sharing Image and Text to Facebook Messenger with Uiactivityviewcontroller Failing
Swiftui Card Flip Animation with Two Views, One of Which Is Embedded Within a Stack