Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pixelize and unpixelize an UIImage or UIImageview?

I would like to pixelize and unpixelize an UIImage or an UIImageview using Swift but I have no idea on how can I do that.

Maybe using effects, layer or something like that?

like image 612
AndrewBr Avatar asked Dec 25 '22 11:12

AndrewBr


1 Answers

This is a very easy task on iOS.

Pixelation

Your can use the CIPixellate Core Image Filter.

func pixellated(image: UIImage) -> UIImage? {
    guard let
        ciImage = CIImage(image: image),
        filter = CIFilter(name: "CIPixellate") else { return nil }
    filter.setValue(ciImage, forKey: "inputImage")
    guard let output = filter.outputImage else { return nil }
    return UIImage(CIImage: output)
}

Result

enter image description here

The default inputScale value is 8. However you can increase or decrease the effect manually setting the parameter.

filter.setValue(8, forKey: "inputScale")
//              ^
//         change this

Extension

You can also define the following extension

extension UIImage {
    func pixellated(scale: Int = 8) -> UIImage? {
        guard let
            ciImage = UIKit.CIImage(image: self),
            filter = CIFilter(name: "CIPixellate") else { return nil }
        filter.setValue(ciImage, forKey: "inputImage")
        filter.setValue(scale, forKey: "inputScale")
        guard let output = filter.outputImage else { return nil }
        return UIImage(CIImage: output)
    }
}

enter image description here

Unpixelation

The mechanism is exactly the same, you just need to use a different filter. You can find the full list of filters here (but take a look at which params are available/required for each filter). I think the CIGaussianBlur can do the job.

Of course don't expect to be able to input a low resolution superpixellated image and get an high definition one. This technology is available only in X-Files :D


The Mushroom image has been taken from here.

like image 148
Luca Angeletti Avatar answered Jan 14 '23 08:01

Luca Angeletti