Why is CGImage creating distorted image sometimes ?

You are going to see two images below. We are getting the image at first square on the left convert it CGImage make some manipulations on it at pixel level and place it 6th square. But at the moment we did inactivated manupulations means we just create a CGImage and convert it back to an UIImage and put it 6th square.


As you can see at top one the image is distorted. I am unable to find reason at the moment.

But sometimes it is OK as it is at second picture.


I lost some time on it and looking for an answer the problem.




http://www.celen.info/bad.jpg

http://www.celen.info/good.jpg


let cgImage = image.cgImage!

let data: NSData = (cgImage.dataProvider?.data)!

var pix2 = [UInt8](data as Data

let numComponents = 4

let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue)

let colorspace = CGColorSpaceCreateDeviceGray()

let rgbData = CFDataCreate(kCFAllocatorDefault, pix2, lenght)!

let provider = CGDataProvider(data: rgbData)!

let resultCGImage = CGImage(width: size_w,

height: size_h,

bitsPerComponent: cgImage.bitsPerComponent,

bitsPerPixel: cgImage.bitsPerPixel,

bytesPerRow: size_w * numComponents,

space: colorspace,

bitmapInfo: bitmapInfo,

provider: provider,

decode: nil,

shouldInterpolate: false,

intent: .defaultIntent)!


let finalUIImage = UIImage(cgImage: resultCGImage)

Replies

You are not showing how you get your `image`, `length`, `size_w`, `size_h`...


If any of these parameters are mismatching with the actual content of your `image` and the parameters given to `CGImage.init`, you get such sort of an image.


Please try to clarify how you get them.

let image = self.imageView[0].image! // This is the ImageView on the left which showing the original image.

let cgImage = image.cgImage!

let size_w = Int (cgImage.width)

let size_h = Int (cgImage.height)

let lenght = size_w * size_h * 4


It it is like this actually. I did not find what was wrong.

Please show the actual number of those values in both cases, successful and distorted.

Additionally the values of `cgImage.bitsPerComponent` and `cgImage.bitsPerPixel` would be some help to solve your issue.

Thanks,

I gave up with this and decided to create custom CIFilter instead and I succeeded too.

Besides it work faster I think than getting pixels values change their values and make an image again with it.


Giving up makes me feel uncomfortable but time is limited.