2015-06-24 65 views
0

我使用此代碼按比例縮小的UIImage應用定向CGContext上

let image = UIImage(contentsOfFile: imageUrl.path!)!.CGImage 

       let width = Float(CGImageGetWidth(image))/1.01 
       let height = Float(CGImageGetHeight(image))/1.01 
       let bitsPerComponent = CGImageGetBitsPerComponent(image) 
       let bytesPerRow = CGImageGetBytesPerRow(image) 
       let colorSpace = CGImageGetColorSpace(image) 
       let bitmapInfo = CGImageGetBitmapInfo(image) 

       let context = CGBitmapContextCreate(nil, Int(width), Int(height), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo) 
       CGContextSetInterpolationQuality(context, kCGInterpolationHigh) 

       CGContextDrawImage(context, CGRect(origin: CGPointZero, size: CGSize(width: CGFloat(width), height: CGFloat(height))), image) 

       let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context)) 

它在照片擴展使用。它起作用,縮放輸入圖像,但不考慮方向。編輯開始時我保持朝向:

func startContentEditingWithInput(contentEditingInput: PHContentEditingInput?, placeholderImage: UIImage) { 

     let output = PHContentEditingOutput(contentEditingInput: self.input) 
     let url = self.input?.fullSizeImageURL 
     if let imageUrl = url { 
      imageOrientation = input!.fullSizeImageOrientation 
     } 

} 

保存的輸出始終爲橫向。

回答

0

這爲我工作:

let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context)) 

       var cimage: CIImage 
       cimage = CIImage(image: scaledImage) 

       if self.imageOrientation != nil { 
        cimage = cimage.imageByApplyingOrientation(self.imageOrientation!) 
       } 
       var _context = CIContext(options: nil) 

       var cgImage = _context.createCGImage(cimage, 
        fromRect: cimage.extent()) 

       var resultImage = UIImage(CGImage: cgImage) 

墊的回答不工作時,我保存圖像。

0

最簡單的解決方案是在創建UIImage輸出時從UIImage輸入重新使用圖像方向。

let uiImage = UIImage(contentsOfFile: imageUrl.path!) 
let image = uiImage!.CGImage 
// ... 
let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context), 
          scale: uiImage.scale, 
          orientation: uiImage.imageOrientation)