I need to convert image to a hexadecimal value. When I try to get a color code of specific pixel on uiimage
I got the wrong value. In Java I'm using bitmap.getpixel()
method to reach pixel color and I'm getting correct value which is 255 but on swift same image pixel returning 0. Do you have any comment on this? or Is there a convenient way to convert image to a hexadecimal?
private func createPrintableObject (img:UIImage) -> String{
let sb = StringBuilder()
let height:Int = Int(img.size.height)
let width:Int = Int(img.size.width)
var index = 0
var rgb:Int,red:Int,green:Int,blue:Int
var rgbColor:UIColor
var auxBinaryChar: [Character] = ["0","0","0","0","0","0","0","0"]
widthBytes = width / 8
if(width % 8 > 0){
widthBytes = ((Int)(width/8))+1
}else{
widthBytes = width / 8
}
self.total = widthBytes * height
let pixelData = img.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
for h in 0...height-1 {
for w in 0...width-1 {
let value = Int(data[((width * w) + h) * 4])
//value returns in Java "-1" but In Swift returning "0"
// JAVA -> rgb = bitmapImage.getPixel(w, h); returning "-1"
red = (value >> 16) & 0x000000FF
green = (value >> 8) & 0x000000FF
blue = (value) & 0x000000FF
let totalColor = red + green + blue
var auxChar = "1"
if(totalColor > self.blackLimit){
auxChar = "0"
}
auxBinaryChar[index] = auxChar[0]
index+=1
if(index == 8 || w == (width-1)){
sb.append(self.fourByteBinary(binaryStr: String(auxBinaryChar)))
auxBinaryChar = ["0","0","0","0","0","0","0","0"]
index = 0
}
}
sb.append("\n")
}
return sb.toString()
}
private func fourByteBinary(binaryStr:String) -> String{
var decimal:Int = Int(binaryStr,radix: 2) ?? 0
if(decimal > 15){
return String(decimal, radix: 16, uppercase: true)
}else{
decimal = Int(String(decimal),radix:16) ?? 0
return "0" + String(decimal, radix: 16, uppercase: true)
}
}
User contributions licensed under CC BY-SA 3.0