将图像上传到Web服务会使图像损坏 [英] Uploading image to web service leaves the image corrupt

查看:100
本文介绍了将图像上传到Web服务会使图像损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从iPhone将图像上传到Web服务,但是即使文件成功上传,也无法查看jpg,它似乎已损坏。

I am trying to upload an image to a web service from an iPhone, but even though the file is successfully uploaded, the jpg cannot be viewed, it seems corrupt.

可以使用以下C#代码成功上传文件并正常工作:

A file can be successfully uploaded and working fine using this c# code:

var url = http://myurl.co.uk/services/service.svc/UploadImage?id=108&ext=png;

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "image/jpeg";

using (var reqStream = req.GetRequestStream())
{
    var bytes = File.ReadAllBytes("C:\\Users\\Chris\\Pictures\\default.png");
    reqStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);

不过,这是我在iOS上尝试执行的代码,导致文件无法显示:

Yet this is the code i'm trying on iOS that leaves the file un-viewable:

获取图像

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    // Resize the image from the camera
    UIImage *scaledImage = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:CGSizeMake(_photo.frame.size.width/2, _photo.frame.size.height/2) interpolationQuality:kCGInterpolationHigh];
    // Crop the image to a square (yikes, fancy!)
    UIImage *croppedImage = [scaledImage croppedImage:CGRectMake((scaledImage.size.width -_photo.frame.size.width)/2, (scaledImage.size.height -_photo.frame.size.height)/2, _photo.frame.size.width, _photo.frame.size.height)];
    // Show the photo on the screen
    _photo.image = croppedImage;

    NSData *imgData=UIImageJPEGRepresentation(croppedImage,1);
    NSLog(@"Original size:%d",[imgData length]);
    NSData *smallerImage=UIImageJPEGRepresentation(croppedImage, 0.5);
    NSLog(@"End size:%d",[smallerImage length]);
    imageData = imgData;

    NSString *imageName = @"tempImage.jpg";
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString * documentsDirectoryPath = [paths objectAtIndex:0];

    NSString *dataPath = [documentsDirectoryPath  stringByAppendingPathComponent:imageName];
    NSData* settingsData = UIImageJPEGRepresentation(croppedImage, 0.5);

    [settingsData writeToFile:dataPath atomically:YES];

    [picker dismissModalViewControllerAnimated:YES];
}

上传图片:

-(void)uploadImageForOfferID:(NSString *)offerID imageExtention:(NSString *)extension withCompletionBlock:(void(^)(NSError *error))block
{
    NSString *imageName = @"tempImage.jpg";
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString * documentsDirectoryPath = [paths objectAtIndex:0];

    NSString *dataPath = [documentsDirectoryPath  stringByAppendingPathComponent:imageName];
    NSData* imageData = [NSData dataWithContentsOfFile:dataPath];

    AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:masterURL]];

    NSString *url = [NSString stringWithFormat:@"UploadImage?id=%@&ext=%@", offerID, extension];
    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    }];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Complete");
        block(nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failed");
        NSLog(@"FAILED WITH STATUS CODE %d - error description: %@", operation.response.statusCode, error.description);
        block(error);
    }];
    [operation start];
}

此方法首先将图像保存到文件,然后上传。我还尝试仅从 NSData * smallerImage = UIImageJPEGRepresentation(croppedImage,0.5); 上传数据,但结果相同。

This method saves the image to a file first then uploads it. I also tried just uploading the data from NSData *smallerImage=UIImageJPEGRepresentation(croppedImage, 0.5); but with the same results.

我在上传时在这里丢失了吗?

Am I missing something here with the upload?

谢谢

编辑----

比较模拟器中的文件和上传的文件。模拟器文件的大小为 2,538字节(磁盘上为4 KB),上传的文件大小为 2,698字节(磁盘为4 KB)
原始模拟器图像显示缩略图,但上传的图像不显示!
可以使用Photoshop打开上传的图像,但不能使用Safari或Chrome打开。

Comparing the file from simulator and the uploaded file. The simulator file is 2,538 bytes (4 KB on disk) and the uploaded file is slightly larger at 2,698 bytes (4 KB on disk) The original simulator image shows a thumbnail, but the uploaded image doesn't! The uploaded image can be opened with Photoshop, but not with Safari or Chrome.

推荐答案

是否可以添加一些内容当您在提供的代码中指向的文件实际上是 .png image / jpeg 的图像怎么办? $ c>文件,应该使用 image / png

Could it have something to do with you sending the image with type image/jpeg when the file you are pointing to in the provided code is actually a .png file and should be using image/png?

这篇关于将图像上传到Web服务会使图像损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆