Advertisement
Guest User

Untitled

a guest
Jun 15th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. - (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
  2. {
  3. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  4. [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
  5. {
  6. if (!error)
  7. {
  8. completionBlock(YES, data);
  9. }
  10. else
  11. {
  12. completionBlock(NO, nil);
  13. }
  14. }];
  15. }
  16.  
  17. UIImage *image = [UIImage imageWithData:serverData];
  18. NSData *jpegData = UIImageJPEGRepresentation(image, 0.75f);
  19.  
  20. CGDataProviderRef imgProvider = CGDataProviderCreateWithCFData((CFDataRef) data);
  21. CGImageRef imgRef = CGImageCreateWithJPEGDataProvider(imgProvider, NULL, true, kCGRenderingIntentDefault);
  22.  
  23. import Foundation
  24. import ImageIO
  25. import MobileCoreServices
  26.  
  27. func saveImageData(_ data: Data, to fileUrl: URL) {
  28. guard let provider = CGDataProvider(data: data as CFData) else {
  29. print("Could not create data provider from data")
  30. return
  31. }
  32.  
  33. guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
  34. print("Could not create cgImage from provider")
  35. return
  36. }
  37.  
  38. guard let imageDestination = CGImageDestinationCreateWithURL(fileUrl as CFURL, kUTTypeJPEG, 1, nil) else {
  39. print("Could not create an image destination from url")
  40. return
  41. }
  42.  
  43. let options = [
  44. kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
  45. kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
  46. ] as CFDictionary
  47.  
  48. CGImageDestinationAddImage(imageDestination, cgImage, options)
  49. let imageIsWritten = CGImageDestinationFinalize(imageDestination)
  50.  
  51. if !imageIsWritten {
  52. print("Image could not be written")
  53. }
  54. }
  55.  
  56. let data: Data = …
  57. let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
  58. let fileUrl = documentDirectoryUrl.appendingPathComponent("image.jpeg")
  59. saveImageData(data, to: fileUrl)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement