Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SwiftでWebPを使ってみた/melon-swift-webp

 SwiftでWebPを使ってみた/melon-swift-webp

http://fablic.connpass.com/event/35407/
で発表したLT資料です

Taketo Yoshida

July 14, 2016
Tweet

More Decks by Taketo Yoshida

Other Decks in Programming

Transcript

  1. 8 // To build libwebp $ brew install libtool $

    brew install automake $ brew install autoconf // Create WebP.framework $ git clone https://chromium.googlesource.com/webm/libwebp $ git checkout 0.5.1 $ ./iosbuild.sh -> WebP.framework Add the WebP Header to your bridging header #include<WebP/decode.h>
  2. 9 private func freeImageData(info: UnsafeMutablePointer<Void>, data: UnsafePointer<Void>, size: Int) {

    free(UnsafeMutablePointer<Void>(data)) } extension UIImage { static func imageFromWebPData(data: NSData) -> UIImage? { var config = WebPDecoderConfig() if WebPInitDecoderConfig(&config) == 0 { return nil } if WebPGetFeatures(UnsafePointer<UInt8>(data.bytes), data.length, &config.input) != VP8_STATUS_OK { return nil } config.output.colorspace = config.input.has_alpha != 0 ? MODE_rgbA : MODE_RGB if WebPDecode(UnsafePointer<UInt8>(data.bytes), data.length, &config) != VP8_STATUS_OK { return nil } let width = config.input.width let height = config.input.height let provider = CGDataProviderCreateWithData(nil, config.output.u.RGBA.rgba, config.output.u.RGBA.size, freeImageData) let colorSpaceRef = CGColorSpaceCreateDeviceRGB() let components = config.input.has_alpha != 0 ? 4 : 3 let bi = config.input.has_alpha != 0 ? CGBitmapInfo(rawValue: CGBitmapInfo.ByteOrderDefault.rawValue | CGImageAlphaInfo.PremultipliedLast.rawValue) : CGBitmapInfo.ByteOrderMask guard let imageRef = CGImageCreate( Int(width), Int(height), 8, components * 8, components * Int(width), colorSpaceRef, bi, provider, nil, true, .RenderingIntentDefault) else { return nil } return UIImage(CGImage: imageRef) } }
  3. 11 guard let url = NSURL(string: "path/to/image") else { return

    } NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in guard let data = data else { return } // Convert NSData to UIImage in Background Threads dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let image = UIImage.imageFromWebPData(data) ?? UIImage(data: data) // Handle image } }