gpt4 book ai didi

ios - 使用 IOS 应用程序将图像上传到服务器文件太大

转载 作者:可可西里 更新时间:2023-11-01 05:33:56 24 4
gpt4 key购买 nike

我正在使用 IOS 应用程序将照片上传到服务器。重要的是上传照片时不要降低质量并以 jpeg 格式上传。我目前的问题是上传的照片没有质量损失,但文件大小比预期的要大。例如:我通过应用程序上传了一个文件,文件大小为 4.7 MB。当我将同一张照片通过电子邮件发送给自己并为电子邮件选择“实际照片”选项时,照片的大小仅为 1.7 MB。并排比较显示质量没有差异。

这是我上传文件的方式。

ALAssetsLibrary *library = [ALAssetsLibrary new];
[library getImageAtURL:orderImage.imageUrl with completionBlock:^(UIImage *image)

NSData *fileData = UIImageJPEGRepresentation(image, 1.0)

NSURLRequest *request = [self multipartFormRequestWithMethod:@"POST" path:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:fileData name:@"uploadedfile" fileName:fileName mimeType:mimeType];
[formData appendPartWithFormData:[extraInfo dataUsingEncoding:NSISOLatin2StringEncoding] name:@"extraInfo"];
}];

最佳答案

问题是 UIImageJPEGRepresentation。它不会检索原始 JPEG,而是创建一个新的 JPEG。当您使用 1compressionQuality(大概是为了避免进一步的图像质量损失)时,它会创建这种没有压缩的新表示(通常会导致文件大于原始文件).

我建议使用 getBytes 检索原始 Assets ,而不是通过 UIImage 来回传输它并通过 UIImageJPEGRepresentation 获取数据:

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:assetsLibraryURL resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *representation = [asset defaultRepresentation];

// I generally would write directly to a `NSOutputStream`, but if you want it in a
// NSData, it would be something like:

NSMutableData *data = [NSMutableData data];

// now loop, reading data into buffer and writing that to our data stream

NSError *error;
long long bufferOffset = 0ll;
NSInteger bufferSize = 10000;
long long bytesRemaining = [representation size];
uint8_t buffer[bufferSize];
while (bytesRemaining > 0) {
NSUInteger bytesRead = [representation getBytes:buffer fromOffset:bufferOffset length:bufferSize error:&error];
if (bytesRead == 0) {
NSLog(@"error reading asset representation: %@", error);
return;
}
bytesRemaining -= bytesRead;
bufferOffset += bytesRead;
[data appendBytes:buffer length:bytesRead];
}

// ok, successfully read original asset;
// do whatever you want with it here

} failureBlock:^(NSError *error) {
NSLog(@"error=%@", error);
}];

--

如果您使用的是 iOS 8 引入的 Photos 框架,可以使用 PHImageManager 获取图像数据:

PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[assetsLibraryURL] options:nil];
PHAsset *asset = [result firstObject];
if (asset) {
PHImageManager *manager = [PHImageManager defaultManager];
[manager requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
// use `imageData` here
}];
}

关于ios - 使用 IOS 应用程序将图像上传到服务器文件太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com