Swift按大小将图片压缩成nsdata

func compressOriginalImage(_ image: UIImage?, toMaxDataSizeKBytes size: CGFloat) -> Data? {

    var data = .uiImageJPEGRepresentation() as? Data

    var dataKBytes: CGFloat = Double((data?.count ?? 0)) / 1000.0

    var maxQuality: CGFloat = 0.9

    var lastData: CGFloat = dataKBytes

    while dataKBytes > size && maxQuality > 0.01 {

        maxQuality = maxQuality - 0.01

        data = .uiImageJPEGRepresentation() as? Data

        dataKBytes = Double((data?.count ?? 0)) / 1000.0

        if lastData == dataKBytes {

            break

        } else {

            lastData = dataKBytes

        }

    }

    return data

}

你可能感兴趣的:(Swift按大小将图片压缩成nsdata)