问题描述
多次使用UIImageJPEGRepresentation(data,1.0)造成内存一直涨,有什么方法取代UIImageJPEGRepresentation方法吗,求大神解答下
问题解答
回答1:那你使用一下UIImagePNGRepresentation
回答2:Instead, create a small buffer, repeatedly filling this buffer with portions of the original asset via getBytes, writing this small buffer to a temporary file using NSOutputStream as you go along.
static NSInteger kBufferSize = 1024 * 10;- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ NSURL *url = info[UIImagePickerControllerReferenceURL]; [self.library assetForURL:url resultBlock:^(ALAsset *asset) {ALAssetRepresentation *representation = [asset defaultRepresentation];long long remaining = representation.size;NSString *filename = representation.filename;NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];NSString *path = [documentsPath stringByAppendingPathComponent:filename];NSString *tempPath = [self pathForTemporaryFileWithPrefix:@'ALAssetDownload'];NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:tempPath append:NO];NSAssert(outputStream, @'Unable to create output stream');[outputStream open];long long representationOffset = 0ll;NSError *error;uint8_t buffer[kBufferSize];while (remaining > 0ll) { NSInteger bytesRetrieved = [representation getBytes:buffer fromOffset:representationOffset length:sizeof(buffer) error:&error]; if (bytesRetrieved < 0) {NSLog(@'failed getBytes: %@', error);[outputStream close];[[NSFileManager defaultManager] removeItemAtPath:tempPath error:nil];return; } else {remaining -= bytesRetrieved;representationOffset += bytesRetrieved;[outputStream write:buffer maxLength:bytesRetrieved]; }}[outputStream close];if (![[NSFileManager defaultManager] moveItemAtPath:tempPath toPath:path error:&error]) { NSLog(@'Unable to move file: %@', error);} } failureBlock:^(NSError *error) {NSLog(@'assetForURL error = %@', error); }];}- (NSString *)pathForTemporaryFileWithPrefix:(NSString *)prefix{ NSString *uuidString = [[NSUUID UUID] UUIDString]; // If supporting iOS versions prior to 6.0, you can use: // // CFUUIDRef uuid = CFUUIDCreate(NULL); // assert(uuid != NULL); // NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid)); // CFRelease(uuid); return [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@'%@-%@', prefix, uuidString]];}