Skip to content
This repository has been archived by the owner on Jan 1, 2023. It is now read-only.

Use cgImage.bytesPerRow instead of width #81

Merged
merged 4 commits into from
May 2, 2021
Merged

Use cgImage.bytesPerRow instead of width #81

merged 4 commits into from
May 2, 2021

Conversation

YuAo
Copy link
Contributor

@YuAo YuAo commented Jan 14, 2021

Because the bitmap data allocated may be padded.

@jathu
Copy link
Owner

jathu commented Mar 19, 2021

@YuAo can you provide more information? What do you mean by the data allocated may be padded?

@YuAo
Copy link
Contributor Author

YuAo commented Mar 20, 2021

@jathu When an image is stored in memory, the memory buffer may contain extra padding bytes after each row of pixels. bytesPerRow is number of bytes allocated for a single row of an image.

Examples:

let cgContext: CGContext = CGContext(data: nil, width: 100, height: 100, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)!
let image: CGImage = cgContext.makeImage()!
image.bytesPerRow //448
image.width * 4 //400

This image object here has the bytesPerRow of 448.


In your case, you use UIGraphicsGetImageFromCurrentImageContext to generate images.

UIGraphicsBeginImageContextWithOptions(CGSize(width: 100, height: 100), false, 1.0)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
image!.cgImage!.bytesPerRow //416
image!.cgImage!.width * 4 //400

This image object here has the bytesPerRow of 416.


So, the index of pixel byte at (x,y) should be y * bytesPerRow + x * 4 instead of ((width * y) + x) * 4.

May be the underlying problem for #65

@jathu
Copy link
Owner

jathu commented Mar 21, 2021

Yup, that makes sense. I think this looks good. Can you also bump the version from 2.2.0 to 2.3.0?

@YuAo
Copy link
Contributor Author

YuAo commented Mar 22, 2021

Can you also bump the version from 2.2.0 to 2.3.0?

Done.

@jathu
Copy link
Owner

jathu commented Mar 22, 2021

Ah, I should've specified the locations but we'll also need to update the version here:

@jathu jathu merged commit f064be8 into jathu:master May 2, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
2 participants