FBImageUtils.m 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. */
  9. #import "FBImageUtils.h"
  10. #import "FBMacros.h"
  11. #import "FBConfiguration.h"
  12. static uint8_t PNG_MAGIC[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
  13. static const NSUInteger PNG_MAGIC_LEN = 8;
  14. BOOL FBIsPngImage(NSData *imageData)
  15. {
  16. if (nil == imageData || [imageData length] < PNG_MAGIC_LEN) {
  17. return NO;
  18. }
  19. static NSData* pngMagicStartData = nil;
  20. static dispatch_once_t oncePngToken;
  21. dispatch_once(&oncePngToken, ^{
  22. pngMagicStartData = [NSData dataWithBytesNoCopy:(void*)PNG_MAGIC length:PNG_MAGIC_LEN freeWhenDone:NO];
  23. });
  24. #pragma clang diagnostic push
  25. #pragma clang diagnostic ignored "-Wassign-enum"
  26. NSRange range = [imageData rangeOfData:pngMagicStartData options:kNilOptions range:NSMakeRange(0, PNG_MAGIC_LEN)];
  27. #pragma clang diagnostic pop
  28. return range.location != NSNotFound;
  29. }
  30. NSData *FBToPngData(NSData *imageData) {
  31. if (nil == imageData || [imageData length] < PNG_MAGIC_LEN) {
  32. return nil;
  33. }
  34. if (FBIsPngImage(imageData)) {
  35. return imageData;
  36. }
  37. UIImage *image = [UIImage imageWithData:imageData];
  38. return nil == image ? nil : (NSData *)UIImagePNGRepresentation(image);
  39. }