iosswiftswift3nsdatauiimagepngrepresentation

Image size is resized when convert it from data in swift 3


I want to save an image in database. Therefore I convert it to Data. However during these steps the width and height of the image will change. It is increased in size.

// Original Image Size
print("Original Image Size : \(capturedImage.size)") // Displays (320.0, 427.0)

// Convert to Data
var imageData: Data?
imageData = UIImagePNGRepresentation(capturedImage)

// Store imageData into Db.

// Convert it back
m_CarImgVw.image = UIImage(data: damageImage!.imageData!, scale: 1.0)
print("m_CarImgVw Image Size : \(m_CarImgVw.image.size)") // Displays (640.0, 854.0)

I do not want the imagesize to increase!


Solution

  • If it’s originally an image from your assets, it’s probably @2x, which means the size in pixels (real size) is double the size in pts (displayed size). So the image size isn’t actually increasing, it was 640x854 before and after the transform. It’s just that before the OS automatically scaled it because it was named @2x.

    To use the original image scale you can replace 1.0 with capturedImage.scale.