Skip to content

Instantly share code, notes, and snippets.

@zhangao0086
Last active July 28, 2021 22:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangao0086/5fafb1e1c0b5d629eb76 to your computer and use it in GitHub Desktop.
Save zhangao0086/5fafb1e1c0b5d629eb76 to your computer and use it in GitHub Desktop.
Convert image to hex. NSImage to byte array
// swift
var image = xxx
var rect = NSRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let cgImage = image.CGImageForProposedRect(&rect, context: nil, hints: nil)!.takeUnretainedValue()
let bitmapRep = NSBitmapImageRep(CGImage: cgImage)
if let imageData = bitmapRep.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:]) {
let len = imageData.length
var bytes = [UInt8](count: len, repeatedValue: 0)
imageData.getBytes(&bytes, length: len)
var result = ""
for i in 0...len - 1 {
if i > 0 {
result += ","
}
result += String(format: "0x%x", arguments: [bytes[i]])
}
println(result)
}
@hidingcat
Copy link

I use this code very helpful. can you show me how convert byte back to image in Mac OS X ? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment