Manipulating an image using Swift has random effects

I have an ImageProcessor in Swift (this is not mine), I'm trying to use it with some filters that I made, but trying to try, I noticed that there was random noise.

To test this, I created my own filter NoFilterthat does nothing.

public class NoFilter : ImageFilterProtocol{
    public func apply(pixel: Pixel) -> Pixel {
        return pixel
    }   
}

This should output the same image that it receives, and sometimes it gives random errors in the image.

For instance:

enter image description here

Please note that this is the same code, and each time it generates different errors. At the end of the question there is a link to try it yourself, each time it works, there may be a different one. What could be the reason?

, ImageProcessor, RGBAImage, , apply , RGBAImage ( ). , , getImage, RGBAImage UIImage. , / RGBAImage, .

public struct RGBAImage {
    public var pixels: UnsafeMutableBufferPointer<Pixel>

    public var width: Int
    public var height: Int

    public init?(image: UIImage) {
        guard let cgImage = image.CGImage else { return nil }

        // Redraw image for correct pixel format
        let colorSpace = CGColorSpaceCreateDeviceRGB()

        var bitmapInfo: UInt32 = CGBitmapInfo.ByteOrder32Big.rawValue
        bitmapInfo |= CGImageAlphaInfo.PremultipliedLast.rawValue & CGBitmapInfo.AlphaInfoMask.rawValue

        width = Int(image.size.width)
        height = Int(image.size.height)
        let bytesPerRow = width * 4

        let imageData = UnsafeMutablePointer<Pixel>.alloc(width * height)

        guard let imageContext = CGBitmapContextCreate(imageData, width, height, 8, bytesPerRow, colorSpace, bitmapInfo) else { return nil }
        CGContextDrawImage(imageContext, CGRect(origin: CGPointZero, size: image.size), cgImage)

        pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height)
    }

    public func toUIImage() -> UIImage? {
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        var bitmapInfo: UInt32 = CGBitmapInfo.ByteOrder32Big.rawValue
        bitmapInfo |= CGImageAlphaInfo.PremultipliedLast.rawValue & CGBitmapInfo.AlphaInfoMask.rawValue

        let bytesPerRow = width * 4

        let imageContext = CGBitmapContextCreateWithData(pixels.baseAddress, width, height, 8, bytesPerRow, colorSpace, bitmapInfo, nil, nil)

        guard let cgImage = CGBitmapContextCreateImage(imageContext) else {return nil}
        let image = UIImage(CGImage: cgImage)

        return image
    }
}

, , .

?

EDIT: git, .

+4
1

, . CGContextClearRect:

let rect = CGRect(origin: CGPointZero, size: image.size)
CGContextClearRect(imageContext, rect)    // Avoid undefined pixels!
CGContextDrawImage(imageContext, rect, cgImage)

undefined - .

+2

Source: https://habr.com/ru/post/1652926/


All Articles