UIImage+WebP.m 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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+WebP.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. if (WebPGetFeatures(data.bytes, data.length, &config.input) != VP8_STATUS_OK) {
  23. return nil;
  24. }
  25. config.output.colorspace = config.input.has_alpha ? MODE_rgbA : MODE_RGB;
  26. config.options.use_threads = 1;
  27. // Decode the WebP image data into a RGBA value array.
  28. if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) {
  29. return nil;
  30. }
  31. int width = config.input.width;
  32. int height = config.input.height;
  33. if (config.options.use_scaling) {
  34. width = config.options.scaled_width;
  35. height = config.options.scaled_height;
  36. }
  37. // Construct a UIImage from the decoded RGBA value array.
  38. CGDataProviderRef provider =
  39. CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData);
  40. CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
  41. CGBitmapInfo bitmapInfo = config.input.has_alpha ? kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast : 0;
  42. size_t components = config.input.has_alpha ? 4 : 3;
  43. CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
  44. CGImageRef imageRef = CGImageCreate(width, height, 8, components * 8, components * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
  45. CGColorSpaceRelease(colorSpaceRef);
  46. CGDataProviderRelease(provider);
  47. UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
  48. CGImageRelease(imageRef);
  49. return image;
  50. }
  51. @end
  52. #if !COCOAPODS
  53. // Functions to resolve some undefined symbols when using WebP and force_load flag
  54. void WebPInitPremultiplyNEON(void) {}
  55. void WebPInitUpsamplersNEON(void) {}
  56. void VP8DspInitNEON(void) {}
  57. #endif
  58. #endif