2

So I have 2 CIImage that I want to merge together, so each with an alpha of 0.5. How can I do it?

I tired the following code but the resulting image is not the correct size and the two images aren't allied correctly... Please help!

if let image = CIImage(contentsOf: imageURL) {
    let randomFilter = CIFilter(name: "CIRandomGenerator")
    let noiseImage = randomFilter!.outputImage!.cropped(to: (CGRect(x: CGFloat(Int.random(in: 1..<1000)), y: CGFloat(Int.random(in: 1..<1000)), width: image.extent.width, height: image.extent.height)))
    let compoimg = noiseImage.composited(over: image) //Misaligned image

} 

misaligned image

AtulParmar
  • 4,358
  • 1
  • 24
  • 45
Jerry Xu
  • 295
  • 2
  • 19
  • Check https://stackoverflow.com/questions/31996715/how-do-i-combine-two-ore-more-ciimage – Onur Tuna Mar 19 '19 at 05:56
  • I did the same thing. It doesn't work. Please provide me with swift examples – Jerry Xu Mar 19 '19 at 06:00
  • Based on the post here https://medium.com/@ranleung/uiimage-vs-ciimage-vs-cgimage-3db9d8b83d94 I think you should use UIImage instead of CIImage to avoid wrong allignment. – Onur Tuna Mar 19 '19 at 06:04

1 Answers1

2

The Problem lies on the random noise generator, because of it's nature that the random noise is cropped from an infinite noise map... the correct code compensates this translation:

if let image = CIImage(contentsOf: imageURL) {
    let randomFilter = CIFilter(name: "CIRandomGenerator")
    let randX = CGFloat(Int.random(in: 0..<1000))
    let randY = CGFloat(Int.random(in: 0..<1000))
    let noiseImage = randomFilter!.outputImage!.cropped(to: (CGRect(x: randX, y: randY, width: image.extent.width, height: image.extent.height)))
    let tt = noiseImage.transformed(by: CGAffineTransform.init(translationX: -randX, y: -randY))
    let compoimg = tt.composited(over: image) //Correctly allied image
}
Jerry Xu
  • 295
  • 2
  • 19
  • You move the origin of the noise image's extent by a random offset (that's why the misalignment above happened) and then you move the origin back to zero with the translation transform. I'm pretty sure you could just use `.cropped(to: image.extent)`. – Frank Rupprecht Mar 19 '19 at 08:07
  • 1
    I could. However, the noise wouldn't be random if the cropping always happen at the same place. – Jerry Xu Mar 20 '19 at 02:33
  • Ah, ok. So it uses the same seed with every invocation? – Frank Rupprecht Mar 20 '19 at 12:09