2017-02-10 80 views
0

我正在开发一个应用程序隐藏文本使用隐写方法称为LSB,将其放入图像。但是在测试过程中,我发现当你在图库中保存一个图像,然后从那里加载图像时,它的RGB值发生了变化。这是红色值:Swift 3 - 保存图像更改RGB值

34 -> 41 
29 -> 34 
44 -> 46 
63 -> 62 
101 -> 105 
118 -> 119 

左 - 他们是什么,对 - 他们成了什么。当然,这样的改变完全破坏了隐藏在里面的文字。这是我用来保存图像的代码:

UIImageWriteToSavedPhotosAlbum(newImg, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil) 


func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { 
     if let error = error { 
      let ac = UIAlertController(title: "Saving error", message: error.localizedDescription, preferredStyle: .alert) 
      ac.addAction(UIAlertAction(title: "OK", style: .default)) 
      present(ac, animated: true) 
     } else { 
      let ac = UIAlertController(title: "Saved!", message: "Saved to the gallery", preferredStyle: .alert) 
      ac.addAction(UIAlertAction(title: "OK", style: .default)) 
      present(ac, animated: true) 
     } 
    } 

这是我提取RGB值的方式:

func pixelData(image: UIImage) -> [UInt8]? { 
    let size = image.size 
    let dataSize = size.width * size.height * 4 
    var pixelData = [UInt8](repeating: 0, count: Int(dataSize)) 
    let colorSpace = CGColorSpaceCreateDeviceRGB() 
    let context = CGContext(data: &pixelData,width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 4 * Int(size.width), space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) 
    guard let cgImage = image.cgImage else { return nil } 
    context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) 

    return pixelData 
} 

我需要一种方法来保存图像,正是因为它是。任何帮助?

编辑1.文字图像注射FUNC:

func encrypt(image: UIImage, message: String) -> UIImage { 

     var text = message 
     text += endSymbols //Need to decrypt message 


     var RGBArray = pixelData(image: image)! 
     let binaryMessage = toBinary(string: text) //Convert characters to binary ASCII number 
     var counter: Int = 0 

     for letter in binaryMessage { 
      for char in letter.characters { 

       let num = RGBArray[counter] 
       let characterBit = char 
       let bitValue = UInt8(String(characterBit)) 
       let resultNum = (num & 0b11111110) | bitValue! 
       RGBArray[counter] = resultNum 
       counter += 4 //Modify only RED values bits 
      } 
     } 

     let resultImg = toImage(data: RGBArray, width: Int(image.size.width), height: Int(image.size.height)) 
     return resultImg! 
    } 
+0

当您保存图像时,它是否为JPEG格式? – Reti43

+0

是的,我在我的.jpg照片和模拟器上的图库上测试了Apple的默认图像 – askrav

+1

因为图像格式有损(可以在存储过程中修改像素以实现压缩),所以不能使用LSB替换的jpg照片。使用bmp,png或其他任何无损格式。 – Reti43

回答

-1

好了,我不知道它是如何工作,但它的工作原理。 我加密保存照片前,加入这样的:

 let imageData = UIImagePNGRepresentation(encryptedImg) 
     encryptedImg = UIImage(data: imageData!)! 

也许这是一个明确的说明符以.png节约。

无论如何,问题解决了。

0

您需要保存为未压缩格式。我不知道如何在swift中编程3.我已经使用ALAssetsLibrary在Objective-c中解决了相同的问题。

+0

这是一个无益的答案,更适合作为评论。评论中已经指出了保存为未压缩格式的必要性。 – Reti43

+0

感谢您的建议。我是一个新人,正在练习回答这个问题。下次我会小心的。 – killerray