Compress image size to 1.5 MB while sending to multipart ios swift

how to compress image size without losing quality in ios swift
how to compress image size in ios programmatically
compress png image swift
xcode image compression
jpeg compression ratio swift
swift heic to jpg
swift reduce image size before upload

I am uploading image with size less than 1.5 MB ( Selecting in imagePickerController) after that I am saving it to Userdefault, but when I am trying to fetch it its size get increase. So at the time of uploading it to Multipart am again trying to compressing it as below. It's giving me "2122 Bytes". That's ok as its less than 1.5 MB. But main issue is I am unable to upload it.

let compressData = UIImage(data:UserDefaultValues.imagep1! as Data)!.jpegData(compressionQuality: 0)

print("length:", UIImage(data:compressData!)!.jpegData(compressionQuality: 0)!)//2122 bytes

let compressData2 = UIImage(data:UserDefaultValues.imagep3! as Data)?.jpegData(compressionQuality: 0) 

print("length2:", UIImage(data:compressData2!)!.jpegData(compressionQuality: 0)!)//2122 bytes

multipartFormData: { multipartFormData in

                    multipartFormData.append(compressData!, withName: "image", fileName: "", mimeType: "image/png")
                    multipartFormData.append("\(storyid)".data(using: .utf8)! , withName: "story_id")
                    multipartFormData.append(compressData2!, withName: "series_image", fileName: "", mimeType: "image/png")
                    multipartFormData.append("\(seriesid)".data(using: .utf8)! , withName: "series_id")


Image Compression extension might help you to maintain sendable image size consistant.

Uploading multipartFormData

 Alamofire.upload(multipartFormData: { multipartFromData in
                    if !fileData.isEmpty {
                        multipartFromData.append(fileData, withName: "file", fileName: "\(UUID().uuidString).png", mimeType: "image/png")

                }, to:URL , method: .post, headers: headers, encodingCompletion: { result in

                    switch result {
                    case .success(let upload, _, _):
                        upload.validate(statusCode: 200 ..< 300).responseString(completionHandler: { _ in
                         print("Upload success")
                    case .failure(let error):

ios - 发送到多部分ios swift时将图像大小压缩到1.5 MB, Compress image size to 1.5 MB while sending to multipart ios swift. 发表于 2019- 11-21 08:22:42. 活跃于 2019-11-22 11:47:13. 查看49 次. ios swift uiimage� This is helpful when you plan to either upload your images online or send it via e-mail. Even sending files via WhatsApp, there are file size restrictions that might prevent you from sending larger images. If you compress images, you can reduce the image’s file size either by a bit or by a lot until you can easily upload or send it.

Here is some step for uploading image on server with sample code

Step1: Upload Image with URLSession

    var croppedImage = UIImage()

    func imageUploadRequest(){
    let getUserData :UserDefaults = UserDefaults.standard
    let User_Id = getUserData.value(forKey: "userid")
    print("userid :\(String(describing: User_Id))!)")
    let myUrl = NSURL(string: "Enter API String Here");
    let request = NSMutableURLRequest(url:myUrl! as URL);
    request.httpMethod = "POST";
    let param = [
        "user_id"  : "\(User_Id!)",

    let boundary = generateBoundaryString()
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    //Pass image in compressImage function
    let compressedImage = self.compressImage(image: croppedImage)
    //Convert It NSData To UIImage and also pass scale value for compression
    convertedImage = UIImage(data:compressedImage as Data,scale:1.0)!
    print("print Lates compress image size : \(convertedImage.size)")
    let imageData = UIImageJPEGRepresentation(convertedImage, 1)
    if(imageData==nil)  { return; }
    request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "fileToUpload", imageDataKey: imageData! as NSData, boundary: boundary) as Data
    //Pass This converted Image To Server
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in
        if error != nil {
            print("error=\(String(describing: error))")
        // You can print out response object
        print("******* response = \(String(describing: response))")
        // Print out reponse body
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("****** response data = \(responseString!)")
        //Show Alert after successfull uploaded
        DispatchQueue.main.async {
            //resolved view is not hiararchy issue.
            let createProfileVC = UIStoryboard(name: "Main", bundle:nil).instantiateViewController(withIdentifier: "CreateProfileViewController") as! CreateProfileViewController
            let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
            appDelegate.window?.rootViewController = createProfileVC
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
            self.imageView.image = nil;

func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
    let body = NSMutableData();
    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString(string: "--\(boundary)\r\n")
            body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString(string: "\(value)\r\n")
    let filename = "profileImage"
    let mimetype = "image/jpg"
    body.appendString(string: "--\(boundary)\r\n")
    body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageDataKey as Data)
    body.appendString(string: "\r\n")

    body.appendString(string: "--\(boundary)--\r\n")

    return body

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().uuidString)"

Step2: Image compression

 //Need to convert NSData to UIImage
func compressImage(image:UIImage) -> NSData {
    // Reducing file size to a 10th

    var actualHeight : CGFloat = image.size.height
    var actualWidth : CGFloat = image.size.width
    var maxHeight : CGFloat = 1136.0
    var maxWidth : CGFloat = 640.0
    var imgRatio : CGFloat = actualWidth/actualHeight
    var maxRatio : CGFloat = maxWidth/maxHeight
    var compressionQuality : CGFloat = 0.5

    if (actualHeight > maxHeight || actualWidth > maxWidth){
        if(imgRatio < maxRatio){
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = maxHeight;
        else if(imgRatio > maxRatio){
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth;
            actualHeight = imgRatio * actualHeight;
            actualWidth = maxWidth;
            actualHeight = maxHeight;
            actualWidth = maxWidth;
            compressionQuality = 1;

    var rect = CGRect(x: 0.0, y:0.0 , width:actualWidth , height: actualHeight)

    image.draw(in: rect)
    var img = UIGraphicsGetImageFromCurrentImageContext();
    let imageData = UIImageJPEGRepresentation(img!, compressionQuality);

    return imageData as! NSData;


extension NSMutableData {

func appendString(string: String) {
    let data = String.Encoding.utf8, allowLossyConversion: true)


In Swift, how to reduce an image f…, What is the need? After taking/importing photo to app, automatically reduce the size of photo while keeping the aspect ratio. For exampe, from 2.3MB at 4:3 ratio � Method 4. Take HEIF/HEIC Photos Instead to Reduce Photo Size in iOS 11. HEIF, also called High Efficiency Image Format, is a new image format (.heic) in iOS 11 which can reduce photo size without compressing image quality. So for iOS 11 devices, Apple offers a way to solve the problem that photos takes a large amount of storage space on iOS


func sendStorySeriesImage(seriesid: Int, storyid: Int){
    let sv = UIViewController.displaySpinner(onView: view)
    guard let compressData2 = (UIImage(data:UserDefaultValues.imagep1! as Data)!).jpegData(compressionQuality: 0.5) else {
    guard let compressData = (UIImage(data:UserDefaultValues.imagep1! as Data)!).jpegData(compressionQuality: 0.5) else {

let url = URL(string: Constants.wevlrBaseUrl + Constants.privateLink + Constants.createstoryseriesImage)!

    multipartFormData: { multipartFormData in

    multipartFormData.append("\(storyid)".data(using: .utf8)! , withName: "story_id")
    multipartFormData.append("\(seriesid)".data(using: .utf8)! , withName: "series_id")
    multipartFormData.append(compressData, withName: "image", fileName: "\(UUID().uuidString).jpg", mimeType: "image/jpg")
    multipartFormData.append(compressData2, withName: "series_image", fileName: "\(UUID().uuidString).jpg", mimeType: "image/jpg")

        to: url,
        method : .post,
        headers : Constants.headers,
        encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):

        upload.responseJSON { response in

            switch response.result {
            case .success(let data):
                UIViewController.removeSpinner(spinner: sv)
                let dict = response.result.value as! NSDictionary
                let statusCode = response.response?.statusCode

                if(statusCode == 201) {
                            UIViewController.removeSpinner(spinner: sv)
                            self.alert(title: "Success!", message: (dict["msg"] as? String)!)

                            UIViewController.removeSpinner(spinner: sv)
                            self.alert(title: "Alert!", message: (dict["msg"] as? String)!)
            case .failure(_):
             self.alert(title: "Alert!", message: "Something went wrong. Please try again.")

        case .failure(_):
         self.alert(title: "Alert!", message: "Something went wrong. Please try again.")


HEIC Image Compression for iOS, In this HEIC image compression tutorial, you'll learn how to transform images While the file's extension, .jpg or .jpeg, can be misleading, JPEG is actually In MainViewController.swift, replace TODO: Add image size here… There is no need to leave your photos with such big size. The following are some little tips to resize iPhone photo size Mb. Tip 1: Resize the Whole Photo Library. Go to "Settings > Photo & Camera". Turn on "iCloud Photo Library". Check "Optimize iPhone Storage". This is one of the easiest ways to reduce iPhone photo file size.

Newest 'uiimage' Questions - Page 3, Compress image size to 1.5 MB while sending to multipart ios swift � ios swift uiimage multipartform-data � Nov 22 '19 at 11:47 Ranu Dhurandhar. -1. 1� You can upload up to 25 images, totally less than 5 MB at a time. All the uploaded pictures will be compressed automatically. To reduce image size on the online image size reducer: Head to FonePaw Online Photo Compressor website. Click on the blue "Add image" button. Choose the pictures you want to shrink image size from the computer.

How to Use this Guide, Then complete an Official BACKPACKER Reader Review form and send it to the If you have, you know that packs come in an array of shapes, sizes, and testers also raved about the compression system, gear access, and user- friendly details. HAMEL/RODALE IMAGES; MICHAEL LANZA; JONATHAN DORN l) While� A large picture of about 20 megapixels (5484x3646) and 5-10 megabytes in most cases can not be compressed to 200-500 KB, but if you specify "size reducing in megapixels" up to 3 or 5, then it will be real, and without the appearance of pixelation (squares) and without jpeg artifacts due to heavy compression. The original image is not changed.

SDK Introduction, In your Build Settings, add -D DEBUG to Debug mode in Other Swift Flags. This can be any JSON object. var variables = { items: { color: 'red', size: 20, The Content-Type of the POST request must be JSON or multipart form data. do this , you can reduce the number of billable calls you make to the Leanplum API ( while� Best way to compress JPG file online. Our fastest online Loseless/Lossy JPG image compressor compress jpg file with best quality. Simple jpg image compressor lets you convert all your jpg images for free.

  • you want to resize image data ..??
  • Yes to 1.5 MB n less....I am getting 2122 bytes but still I am getting that Image size should not be more than 1.5 MB :(
  • @RanuDhurandhar Have you used " UIImageJPEGRepresentation " function for UIImage ? OR you have to change your compressionQuality: 0 to compressionQuality: 0.5
  • I want to compress the size for 1.5 MB.
  • i will try this
  • You can manage desire compression size by using compressionQuality parameter.