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

1.4k views Asked by At

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!

2

There are 2 answers

0
David Berry On BEST ANSWER

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.

0
user28434'mstep On

Your problem is in this line:

m_CarImgVw.image = UIImage(data: damageImage!.imageData!, scale: 1.0)

Can you see it?

Hint: It's in scale: 1.0.

It looks like your original image was Retina (or @2x), so it had scale 2.0.

So you should either put your original image scale (damageImage.scale) there, or if you're presenting image on the screen you should use UIScreen's scale.