【问题标题】:Send image to server as binary data将图像作为二进制数据发送到服务器
【发布时间】:2010-02-24 04:42:46
【问题描述】:

我想制作一个 iPhone 应用程序来将图像发送到我的服务器。

我想在 iPhone 中绘制一些东西(例如:签名)作为图像以将二进制图像 POST 到我的服务器(服务器是 JSP)。请告诉我该怎么办?

  • 如何使用 iPhone 用户界面?
  • 如何从图像等中生成二进制数据

【问题讨论】:

    标签: iphone


    【解决方案1】:

    首先,您可以使用 UIImagePNGRepresentation 和 UIImageJPEGRepresentation 函数获取包含图像数据的 PNG 或 JPEG 表示的 NSData 对象。

    // To get the data from a PNG file
    NSData *dataForPNGFile = UIImagePNGRepresentation(yourImage);
    
    // To get the data from a JPEG file
    NSData *dataForPNGFile = UIImageJPEGRepresentation(yourImage, 0.9f);
    

    (更多信息请参阅:UIImage Class Reference

    要完成将数据从 iPhone 上传到服务器,您可以这样做:

    - (void)sendImage {
           NSData *postData = [nsdata from your original image];
           NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
           // Init and set fields of the URLRequest
           NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
           [request setHTTPMethod:@"POST"];
           [request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]];
           [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
           [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
           [request setHTTPBody:postData];
    
           NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
           if (connection) {
              // Return data of the request
              NSData *receivedData = [[NSMutableData data] retain];
           }
           [request release];
     }
    

    【讨论】:

    • 感谢您的回答。在您的指南上方,NSData 是从任何地方都存在的 PNG/JPEG 文件中获取的。但我想直接在 iPhone 中绘制签名并从中获取 NSData。我该怎么办?
    • 如果您还想在发布请求中在服务器上设置几个变量怎么办?
    • 这个问题快2岁了!要回答发帖人的原始问题和后续问题:在 Yannick 的回复中,您会看到“yourImage”值。该值应该代表图像的 UIImage 。因此,如果您在屏幕上绘制图像,并将图像的屏幕截图捕获到名为“myImageView”的 UIImageView 中,您将通过“myImageView.image”引用包含在该 ImageView 中的 UIImage。 UIImage 然后将被翻译/序列化为二进制数据(使用上述方法),该数据将附加到您的 URLRequest。我希望能澄清事情。 :)
    【解决方案2】:

    使用drawrect 方法对UIImage 进行签名。为此,您必须使用 UITouch 代表

    并使用以下内容将您的 UIImage 对象转换为 NSData

    // To get the data from a PNG file
    
    NSData *dataForPNGFile = UIImagePNGRepresentation(yourImage);
    
    // To get the data from a JPEG file
    
    NSData *dataForPNGFile = UIImageJPEGRepresentation(yourImage, 0.9f);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 2012-09-10
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多