Imageview图片未正确设置或过滤

时间:2018-02-25 20:21:17

标签: ios swift ciimage imagefilter

我有一个imageview,我通过使用相机或图库设置其图像,然后使用ciImage为其添加过滤器。 问题是,当我将滤镜应用于该图像,然后将该图像设置回imageview时,它会在一些间隙后开始。我没有问题,但它应该在两侧同样保持原始图像方面。    filter on captured photo when opening captured image in Photos app并且黑色部分仅是imageview的一部分(在调试视图层次结构中检查)

captuingImageController(捕获图像并将图像发送到) - > filterViewController(过滤并设置图像)

奇怪的是,它并没有发生在所有图像上,只有我用这个应用程序捕获的图像。但如果我不过滤图像并直接完成其设置。因此,不了解问题的位置,是过滤还是捕获图像。 PS:如果我用Photos app打开相同的图像,它看起来很好。

这是用于向图像添加过滤器的代码。

 override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.isHidden = true
    self.selectedImageView.image  = image

    //------ if I comment out the below filtering part image lookes perfect but if i use image not center with scaleAspectFill.
    self.selectedImageView.contentMode = .scaleAspectFit
    guard let image = image, let cgimg = image.cgImage else {
        print("imageView doesn't have an image!")
        return
    }
    let coreImage = CIImage(cgImage: cgimg)
    let filter = CIFilter(name: "CISepiaTone")
    filter?.setValue(coreImage, forKey: kCIInputImageKey)
    filter?.setValue(1, forKey: kCIInputIntensityKey)

    if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage {
        let filteredImage: UIImage = UIImage(ciImage: output)
        selectedImageView?.image = filteredImage
        UIImageWriteToSavedPhotosAlbum(filteredImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)            
        self.selectedImageView.contentMode = UIViewContentMode.scaleAspectFill
    } else {
        print("image filtering failed")
    }
    // ------
} 

捕获图像后的代码

public func photoOutput(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?,
                        resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Swift.Error?) {
    if let error = error { self.photoCaptureCompletionBlock?(nil, error) }

    else if let buffer = photoSampleBuffer, let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: buffer, previewPhotoSampleBuffer: nil),
        var image = UIImage(data: data) {
        if currentCameraPosition == .front {
            image = UIImage(cgImage: image.cgImage!, scale: image.scale, orientation: .leftMirrored)
        }

        self.photoCaptureCompletionBlock?(image, nil)
    }

    else {
        self.photoCaptureCompletionBlock?(nil, CameraControllerError.unknown)
    }
}

而且我必须添加不同的过滤器,基于用户向左或向右滑动,如instagarm,还添加裁剪功能,方形,矩形和比率和许多很酷的东西,但首先这个演示的东西是不完美的工作:-(如果你有任何教程或示例代码正在做所有这些事情,请提前分享链接

filter on old pic from gallery

1 个答案:

答案 0 :(得分:0)

在应用滤镜存储比例和方向时仅缺少一个线设置比例和原始图像的方向,然后在转换回uiImage时将其设置回来

let filteredImage  = UIImage(cgImage:filteredImageRef!, scale:imgScale!, orientation:imgOrientation!)