1

I have an UnsafeMutablePointer<UInt8> which contains the raw RGB data to construct the image.

But I cannot find a API that can render the image from raw RGB data.

var content = UnsafeMutablePointer<UInt8>.allocate(capacity: 6)
apply_raw_data(content) // set content to [255,0,0,255,0,0]
let data = Data(bytes: content, count: 6)
let ui_image = UIImage(data: data) // we get nil
qdwang
  • 425
  • 1
  • 4
  • 13
  • Does this answer your question? [create image from rgb data in swift](https://stackoverflow.com/questions/67152169/create-image-from-rgb-data-in-swift) – Ramesh Sanghar Oct 05 '22 at 04:27
  • or this one : https://stackoverflow.com/questions/7235991/create-image-from-rgb-data – Ramesh Sanghar Oct 05 '22 at 04:28
  • If the data is valid, the most simple way is use `CIImage.init(data:)`, then convert to UIImage with `UIImage.init(ciImage:)` – Tj3n Oct 05 '22 at 06:56

1 Answers1

0

One way to do it is by creating an intermediate CGImage from a CGContext. However, this solution will require you to use RGBA (or ARGB) and not RGB as you actually asked about.

let width = 2
let height = 1
let bytesPerPixel = 4 // RGBA

let content = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height * bytesPerPixel)
apply_raw_data(content) // set content to [255,0,0,0,255,0,0,0]

let colorSpace = CGColorSpaceCreateDeviceRGB()    

guard let context = CGContext(data: content, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
    else { return }
    
if let cgImage = context.makeImage() {
    let image = UIImage(cgImage)
    // use image here
}
gekart
  • 143
  • 7