UIImage+EMWebP.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // UIImage+WebP.m
  3. // SDWebImage
  4. //
  5. // Created by Olivier Poitrey on 07/06/13.
  6. // Copyright (c) 2013 Dailymotion. All rights reserved.
  7. //
  8. #ifdef SD_WEBP
  9. #import "UIImage+EMWebP.h"
  10. #import "webp/decode.h"
  11. // Callback for CGDataProviderRelease
  12. static void FreeImageData(void *info, const void *data, size_t size)
  13. {
  14. free((void *)data);
  15. }
  16. @implementation UIImage (WebP)
  17. + (UIImage *)sd_imageWithWebPData:(NSData *)data {
  18. WebPDecoderConfig config;
  19. if (!WebPInitDecoderConfig(&config)) {
  20. return nil;
  21. }
  22. config.output.colorspace = MODE_rgbA;
  23. config.options.use_threads = 1;
  24. // Decode the WebP image data into a RGBA value array.
  25. if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) {
  26. return nil;
  27. }
  28. int width = config.input.width;
  29. int height = config.input.height;
  30. if (config.options.use_scaling) {
  31. width = config.options.scaled_width;
  32. height = config.options.scaled_height;
  33. }
  34. // Construct a UIImage from the decoded RGBA value array.
  35. CGDataProviderRef provider =
  36. CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData);
  37. CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
  38. CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast;
  39. CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
  40. CGImageRef imageRef = CGImageCreate(width, height, 8, 32, 4 * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
  41. CGColorSpaceRelease(colorSpaceRef);
  42. CGDataProviderRelease(provider);
  43. UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
  44. CGImageRelease(imageRef);
  45. return image;
  46. }
  47. @end
  48. #if !COCOAPODS
  49. // Functions to resolve some undefined symbols when using WebP and force_load flag
  50. void WebPInitPremultiplyNEON(void) {}
  51. void WebPInitUpsamplersNEON(void) {}
  52. void VP8DspInitNEON(void) {}
  53. #endif
  54. #endif