1

I have a pixel array from which UIImage needs to be created. The pixel array uses 4 bytes for each pixel in RGBA format. i.e. 00000000 - is black transparent and 000000ff - is black opaque.

The UIImage is to be created using swift and xcode 6.3 or greater.

Need to loop through the pixel array, get every four bytes for each pixel and create image from the pixels.

Could see objective c references, but not clear code sample for swift.

3
  • Where are the objective c reference ? I can translate them in swift for you Commented Jul 5, 2015 at 6:21
  • What does create an image with a color mean? Commented Jul 5, 2015 at 9:35
  • Check out this question. stackoverflow.com/q/30958427/1630618 Commented Jul 5, 2015 at 10:07

1 Answer 1

1

Here is a sample that I use to create CGImages from an RGBA byte array:

struct m_RGBColor // My own data-type to hold the picture information
{
    var Alpha: UInt8 = 255
    var Red:   UInt8 = 0
    var Green: UInt8 = 0
    var Blue:  UInt8 = 0
}

var pixelArray: [m_RGBColor] = [m_RGBColor]()
var pixelColor: m_RGBColor = m_RGBColor()

for y in 0 ..< height // Height of your Pixture
{
    for x in 0 ..< width // Width of your Picture
    {
        onePixel.Alpha = 0 // Fill one Pixel with your Picture Data
        onePixel.Red   = 0 // Fill one Pixel with your Picture Data
        onePixel.Green = 0 // Fill one Pixel with your Picture Data
        onePixel.Blue  = 0 // Fill one Pixel with your Picture Data
        pixelArray.append(onePixel)
    }
}

let bitmapCount: Int = pixelArray.count
let elmentLength: Int = sizeof(m_RGBColor)
let render: CGColorRenderingIntent = CGColorRenderingIntent.RenderingIntentDefault
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
let providerRef: CGDataProvider? = CGDataProviderCreateWithCFData(NSData(bytes: &pixelArray, length: bitmapCount * elmentLength))
let cgimage: CGImage? = CGImageCreate(width, height, 8, 32, width * elmentLength, rgbColorSpace, bitmapInfo, providerRef, nil, true, render)
if cgimage != nil
{
    // You have success, the Image is valid and usable
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.