iOS: Get displayed image size in pixels

Swift 5

Take a Look here

// This extension to save ImageView as UImage
    extension UIView {
        func asImage() -> UIImage {
            let renderer = UIGraphicsImageRenderer(bounds: bounds)
            return renderer.image { rendererContext in
                layer.render(in: rendererContext.cgContext)
            }
        }
    }

    // this extension to resize image 
    extension UIImage {
      func resizeImage(targetSize: CGSize) -> UIImage {
        let size = self.size
        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height
        let newSize = widthRatio > heightRatio ?  CGSize(width: size.width * heightRatio, height: size.height * heightRatio) : CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
      }
    }

    // This extension will display image with 300X300 pixels
    extension UIImage {
    func Size300X300() -> UIImage? {
            let imageView = UIImageView()
             imageView.contentMode = .scaleAspectFit
             imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
             let image = imageView.asImage()
             let newImage = image.resizeImage(targetSize: CGSize(width:300, height: 300))
             return newImage

          }
    }
     let image = YOURIMAGE.Size300X300()
     imageView.image = image!

To get size in pixels of UIImageView:

let widthInPixels = imageView.frame.width * UIScreen.mainScreen().scale
let heightInPixels = imageView.frame.height * UIScreen.mainScreen().scale

To get size in pixels of UIImage:

let widthInPixels = image.size.width * image.scale
let heightInPixels = image.size.height * image.scale

Tags:

Ios

Cocoa

Swift