在将高分辨率图像发送到swift中的苹果手表之前将其缩放

时间:2016-09-01 11:40:31

标签: ios swift uiimage apple-watch

在我的应用程序中,我想缩放我的图像,该图像被发送到Apple Watch,因为在模拟器中没有问题,但是当从真实设备发送时,有效负载大小限制会起作用。我还想知道在使用手表连接时使用发送消息方法时苹果手表可以承受多少有效负载。

我的观看应用的源代码:

    class InterfaceController: WKInterfaceController, WCSessionDelegate {

    var session: WCSession!

    var MessageData = NSMutableDictionary()

    @IBOutlet var watch_displayImage: WKInterfaceImage!
    @IBOutlet var watch_ticket_category: WKInterfaceLabel!
    @IBOutlet var watch_ticketType: WKInterfaceLabel!
    @IBOutlet var watch_ticketTime: WKInterfaceLabel!
    @IBOutlet var watch_ticketDate: WKInterfaceLabel!

    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)

        if WCSession.isSupported()
        {

            session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()

        }

    }

    override func willActivate()
    {

        super.willActivate()

    }

    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void)
    {

        //print(message.values)

        MessageData = NSMutableDictionary(object: message, forKey: "data")
        print("\(MessageData)")
        watch_ticket_category.setText("\(MessageData["data"]!["Watchdat"]!!["ticket_category"] as! String)")
        watch_displayImage.setImage(UIImage(named: MessageData["data"]!["Watchdat"]!!["imagePath"] as! String))
        watch_ticketType.setText("\(MessageData["data"]!["Watchdat"]!!["ticket_type"] as! String)")
        watch_ticketTime.setText("\(MessageData["data"]!["Watchdat"]!!["time"] as! String)")
        watch_ticketDate.setText("\(MessageData["data"]!["Watchdat"]!!["date"] as! String)")


   }

我的IOS应用程序的源代码:

    class TicketDetailViewController: UIViewController, WCSessionDelegate {
  let dic1  = NSMutableDictionary()
    var defaults = NSUserDefaults()
    var databasePath = NSString()
    var holding_Ticket_category: String = ""
    var holding_Image: UIImage?
    var hold_ticketName: String = ""
    var hold_ticketDate: String = ""
    var hold_ticketTime: String = ""
    var session: WCSession!
    var imageData: NSData!

    @IBOutlet weak var ticket_grey: UIImageView!
    @IBOutlet weak var cropped_frame: UIImageView!
    @IBOutlet weak var display_image: UIImageView!
    @IBOutlet weak var ticket_type_name: UILabel!
    @IBOutlet weak var ticket_date: UILabel!
    @IBOutlet weak var ticket_time: UILabel!
    @IBOutlet weak var ticket_category: UILabel!


    override func viewDidLoad()
    {
        super.viewDidLoad()
        if WCSession.isSupported(){
            self.session  = WCSession.defaultSession()
            self.session.delegate = self
            self.session.activateSession()
        }

        defaults = NSUserDefaults.standardUserDefaults()
        display_image.image = self.holding_Image
        ticket_type_name.text = hold_ticketName
        ticket_date.text = hold_ticketDate
        ticket_time.text = hold_ticketTime
        ticket_category.text = holding_Ticket_category

        let filemgr =  NSFileManager.defaultManager()
        let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let docsDir = dirPaths[0]
        var ticketDB: FMDatabase

        databasePath = (docsDir as NSString).stringByAppendingPathComponent("ticket_Pass.sqlite")


        if !filemgr.fileExistsAtPath(databasePath as String)
        {

            ticketDB = FMDatabase(path: databasePath as String)
            if ticketDB.open()
            {

                let sql_stmt = "CREATE TABLE IF NOT EXISTS TICKET (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMAGEPATH TEXT, IMAGENAME TEXT, TICKET_CATEGORY TEXT, TICKET_TYPE TEXT, DATE TEXT, TIME TEXT)"
                if !ticketDB.executeStatements(sql_stmt)
                {
                    print("Error: \(ticketDB.lastErrorMessage())")
                }
                ticketDB.close()
            } else
            {
                 print("Error: \(ticketDB.lastErrorMessage())")
            }
        }else{
            ticketDB = FMDatabase(path: databasePath as String)
            if ticketDB.open()
            {

                let sql_stmt = "CREATE TABLE IF NOT EXISTS TICKET (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMAGEPATH TEXT, IMAGENAME TEXT, TICKET_CATEGORY TEXT, TICKET_TYPE TEXT, DATE TEXT, TIME TEXT)"
                if !ticketDB.executeStatements(sql_stmt)
                {
                    print("Error: \(ticketDB.lastErrorMessage())")
                }
                ticketDB.close()
            } else
            {

                print("Error: \(ticketDB.lastErrorMessage())")
            }

        }
    }

    func saveImageToFolder()
    {

        imageData = UIImagePNGRepresentation(holding_Image!)!
        let imageName = "image_\(NSDate.timeIntervalSinceReferenceDate()).png"
        let imagePath = (self.getDocumentsDirectory() as NSString).stringByAppendingPathComponent(imageName)
        print("imagePath:- \(imagePath)")
        print("image size: \(holding_Image?.size)")

        imageData.writeToFile(imagePath, atomically: true)
        NSUserDefaults.standardUserDefaults().setObject(imagePath, forKey: "ImagePath")
        NSUserDefaults.standardUserDefaults().setObject(imageData, forKey: "ImageData")
        NSUserDefaults.standardUserDefaults().setObject(imageName, forKey: "ImageName")
        NSUserDefaults.standardUserDefaults().synchronize()

    }

    func getDocumentsDirectory() -> String{
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsPath = paths[0]
        print("document path:- \(documentsPath)")
        return documentsPath

    }

  @IBAction func addTickets(sender: UIButton)
  {

        let ticketDB = FMDatabase(path: databasePath as String)
        if ticketDB.open()
        {
                //self.saveImageToFolder()
                let insertSQL = "INSERT INTO TICKET (imagePath, imageName, ticket_category, ticket_type, date, time) VALUES ('\(NSUserDefaults.standardUserDefaults().objectForKey("ImagePath")!)', '\(NSUserDefaults.standardUserDefaults().objectForKey("ImageName")!)', '\(ticket_category.text!)', '\(ticket_type_name.text!)', '\(ticket_date.text!)', '\(ticket_time.text!)')"

                let result = ticketDB.executeUpdate(insertSQL,withArgumentsInArray: nil)

                if !result
                {

                    print("Error: \(ticketDB.lastErrorMessage())")

                } else
                {

                    let alt = PMAlertController(title: "Success!", description: "Your data is saved to Database!", image: UIImage(named: ""), style: .Alert)

                    alt.addAction(PMAlertAction(title: "OK!", style: .Default, action: { (ACTION) -> Void in

                    self.navigationController?.popToRootViewControllerAnimated(true)

                    }))

                    self.presentViewController(alt, animated: true, completion: nil)
                    print(databasePath)

               }
        }
    }


    @IBAction func deleteTickets(sender: UIButton) {
        let alt = PMAlertController(title: "Delete Ticket Details!", description: "Are you sure?", image: UIImage(named: ""), style: .Alert)

        alt.addAction(PMAlertAction(title: "Cancel", style: PMAlertActionStyle.Default, action: { (ACTION) -> Void in

            self.dismissViewControllerAnimated(true, completion: nil)

        }))
        alt.addAction(PMAlertAction(title: "OK", style: PMAlertActionStyle.Default, action: { (ACTION) -> Void in

            self.navigationController?.popToRootViewControllerAnimated(true)
        }))
        self.presentViewController(alt, animated: true, completion: nil)
    }


    @IBAction func sendToWatch(sender: AnyObject)
    {

        let ticketDB = FMDatabase(path: databasePath as String)
        if ticketDB.open()
        {
            self.saveImageToFolder()
            let insertSQL = "INSERT INTO TICKET (imagePath, imageName, ticket_category, ticket_type, date, time) VALUES ('\(NSUserDefaults.standardUserDefaults().objectForKey("ImagePath")!)', '\(NSUserDefaults.standardUserDefaults().objectForKey("ImageName")!)', '\(ticket_category.text!)', '\(ticket_type_name.text!)', '\(ticket_date.text!)', '\(ticket_time.text!)')"

            let result = ticketDB.executeUpdate(insertSQL,withArgumentsInArray: nil)

            if !result
            {

                print("Error: \(ticketDB.lastErrorMessage())")

            } else
            {

                let alt = PMAlertController(title: "Success!", description: "Your data is saved!", image: UIImage(named: ""), style: .Alert)

                alt.addAction(PMAlertAction(title: "OK!", style: .Default, action:
                { (ACTION) -> Void in


                        let ticketDB = FMDatabase(path: self.databasePath as String)
                        if ticketDB.open()
                        {

//                            let querySQL = "SELECT * FROM TICKET ORDER BY ID DESC LIMIT 1"
                             let querySQL = "SELECT * FROM TICKET "

                            let result: FMResultSet? = ticketDB.executeQuery(querySQL, withArgumentsInArray: nil)

                            if let result = result
                            {

                                let ticketDataArray:NSMutableArray = NSMutableArray()
                                while result.next()
                                {

                                    self.dic1.setObject(result.stringForColumn("imagePath"), forKey: "imagePath")
                                    self.dic1.setObject(result.stringForColumn("imageName"), forKey: "imageName")
                                    self.dic1.setObject(result.stringForColumn("ticket_category"), forKey: "ticket_category")
                                    self.dic1.setObject(result.stringForColumn("ticket_type"), forKey: "ticket_type")
                                    self.dic1.setObject(result.stringForColumn("date"), forKey: "date")
                                    self.dic1.setObject(result.stringForColumn("time"), forKey: "time")

                                    ticketDataArray.addObject(self.dic1)

                                }
                                print("ticketDataArray :  \(self.dic1)")
                            }else
                            {
                                print("Error: \(ticketDB.lastErrorMessage())")

                            }

                          ticketDB.close()

                        }
                      self.navigationController?.popToRootViewControllerAnimated(true)
                        if WCSession.defaultSession().reachable
                        {
                            let dict = ["Watchdat":self.dic1]

                            self.session.sendMessage(dict, replyHandler: { (replayDic: [String:AnyObject]) in
                                print("success!")
                                }, errorHandler: { (error:NSError) in
                                    print("error")
                            })
                        }

                }))

                self.presentViewController(alt, animated: true, completion: nil)
                print(databasePath)

            }
        }

screenshot for my app

1 个答案:

答案 0 :(得分:0)

我们使用最大像素方法进行缩放。您可以尝试重新调整大小,直到达到所需的阈值

#define MAX_PIXEL_SIZE 800


CGImageRef createScreenShotWithRestrectedSize(NSData * screenShotData, int maxPixelSize)
{
    CGImageRef        myScreenShot = NULL;
    CGImageSourceRef  myImageSource;
    CFDictionaryRef   myOptions = NULL;
    CFStringRef       myKeys[3];
    CFTypeRef         myValues[3];
    CFNumberRef       screenShotMaxPixelSize;

    myImageSource = CGImageSourceCreateWithData((CFDataRef)screenShotData,
                                                NULL);

    if (myImageSource == NULL){
        fprintf(stderr, "Image source is NULL.");
        return  NULL;
    }

    screenShotMaxPixelSize = CFNumberCreate(NULL, kCFNumberIntType, &maxPixelSize);

    //Create image options:
    // 0: Allow image transformation (rescale and oriantation)
    myKeys[0] = kCGImageSourceCreateThumbnailWithTransform;
    myValues[0] = (CFTypeRef)kCFBooleanTrue;
    // 1: Always create a Thumbnail, even if the image has one
    myKeys[1] = kCGImageSourceCreateThumbnailFromImageAlways;
    myValues[1] = (CFTypeRef)kCFBooleanTrue;
    // 2: Set height and width maxPixel size
    myKeys[2] = kCGImageSourceThumbnailMaxPixelSize;
    myValues[2] = (CFTypeRef)screenShotMaxPixelSize;

    myOptions = CFDictionaryCreate(NULL, (const void **) myKeys,
                                   (const void **) myValues, 3,
                                   &kCFTypeDictionaryKeyCallBacks,
                                   & kCFTypeDictionaryValueCallBacks);

    // Create image with above options
    myScreenShot = CGImageSourceCreateThumbnailAtIndex(myImageSource,
                                                           0,
                                                           myOptions);

    // Release resources
    CFRelease(screenShotMaxPixelSize);
    CFRelease(myOptions);
    CFRelease(myImageSource);

    // Make sure the thumbnail image exists before continuing.
    if (myScreenShot == NULL){
        fprintf(stderr, "Screen shot image does not exists");
        return NULL;
    }

    return myScreenShot;
}

NSData *dataCapturedScreen = UIImageJPEGRepresentation(img,1);

    //Create an image that will have a 60kb size restriction
CGImageRef ir = createScreenShotWithRestrectedSize(dataCapturedScreen, MAX_PIXEL_SIZE);
UIImage *restrictedSizeImage = [UIImage imageWithCGImage:ir];
CGImageRelease(ir);
NSData *imageData = UIImageJPEGRepresentation(restrictedSizeImage, 0.5);