Last active
July 28, 2021 22:22
-
-
Save zhangao0086/5fafb1e1c0b5d629eb76 to your computer and use it in GitHub Desktop.
Convert image to hex. NSImage to byte array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this code very helpful. can you show me how convert byte back to image in Mac OS X ? Thank you.