Convert Uiview to .Png in Swift

Convert UIView to .png in Swift

Try this:

UIGraphicsBeginImageContextWithOptions(myView.layer.frame.size, false, scale)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()!
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


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() {

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


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();

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:, 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;

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


if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) {
imageView.contentMode = .scaleAspectFit
imageView.image = image


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)


override func viewDidLoad() {
print("Begin of code")
let url = URL(string: "")!
downloadImage(from: url)
print("End of code. The image will continue downloading in the background and it will be loaded when it ends.")


extension UIImageView {
func downloaded(from url: URL, contentMode mode: ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
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
func downloaded(from link: String, contentMode mode: ContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)


imageView.downloaded(from: "")

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

Related Topics

Leave a reply