Compressing Images for PDFKit

NSData *jpegData = UIImageJPEGRepresentation(sourceImage, 0.75);
CGDataProviderRef dp = CGDataProviderCreateWithCFData((__bridge CFDataRef)jpegData);
CGImageRef cgImage = CGImageCreateWithJPEGDataProvider(dp, NULL, true, kCGRenderingIntentDefault);
[[UIImage imageWithCGImage:cgImage] drawInRect:drawRect];

Can someone please translate this to Swift 5 for me?

I'm trying to figure out how to get PDFKit to print the ResizedImage and not the RAW image. I think this may be the solution to my problem, but it's outdated and in another language... I think. I'm a beginner.


Here you go:

import UIKit

let sourceImage: UIImage = ...
let drawRect: CGRect = ...

guard let jpegData = sourceImage.jpegData(compressionQuality: 0.75),
      let dp = CGDataProvider(data: jpegData as CFData),
      let cgImage = CGImage(jpegDataProviderSource: dp, decode: nil, shouldInterpolate: true, intent: .defaultIntent) else {
  // TODO: Handle errors appropriately
  fatalError("Some operation failed")
UIImage(cgImage: cgImage).draw(in: drawRect)
Terms of Service

Privacy Policy

Cookie Policy