UTMScreenshot.m 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // Copyright © 2020 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. #import "TargetConditionals.h"
  17. #import "UTMScreenshot.h"
  18. @implementation UTMScreenshot
  19. - (instancetype)init {
  20. return [super init];
  21. }
  22. #if TARGET_OS_IPHONE
  23. - (instancetype)initWithImage:(UIImage *)image {
  24. if (self = [self init]) {
  25. _image = image;
  26. }
  27. return self;
  28. }
  29. - (instancetype)initWithContentsOfURL:(NSURL *)url {
  30. if (self = [self init]) {
  31. _image = [[UIImage alloc] initWithContentsOfFile:url.path];
  32. if (_image == nil) {
  33. self = nil;
  34. }
  35. }
  36. return self;
  37. }
  38. - (void)writeToURL:(NSURL *)url atomically:(BOOL)atomically {
  39. [UIImagePNGRepresentation(_image) writeToURL:url atomically:atomically];
  40. }
  41. #else
  42. - (instancetype)initWithImage:(NSImage *)image {
  43. if (self = [self init]) {
  44. _image = image;
  45. }
  46. return self;
  47. }
  48. - (instancetype)initWithContentsOfURL:(NSURL *)url {
  49. if (self = [self init]) {
  50. _image = [[NSImage alloc] initWithContentsOfURL:url];
  51. if (_image == nil) {
  52. self = nil;
  53. }
  54. }
  55. return self;
  56. }
  57. - (void)writeToURL:(NSURL *)url atomically:(BOOL)atomically {
  58. CGImageRef cgRef = [self.image CGImageForProposedRect:NULL
  59. context:nil
  60. hints:nil];
  61. NSBitmapImageRep *newRep = [[NSBitmapImageRep alloc] initWithCGImage:cgRef];
  62. [newRep setSize:[self.image size]]; // if you want the same resolution
  63. NSData *pngData = [newRep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
  64. [pngData writeToURL:url atomically:atomically];
  65. }
  66. #endif
  67. @end