Golang 为 jpeg 图像生成一致的哈希值,无需写入磁盘

问题描述 投票:0回答:1

golang 成像新手

我正在尝试为 jpeg 图像生成一致的哈希值。 当我以 JPEG 格式写入磁盘(这是预期的)后重新加载图像时,加载图像并在原始字节上生成哈希值会产生不同的哈希值。一旦我将 RBGA 作为 JPEG 写入磁盘,像素就会被修改,这会破坏我之前计算的哈希值。

仅对文件进行哈希处理

hash("abc.jpeg")
就意味着我必须写入磁盘;读回;生成哈希值等..

  • 在读取/写入时我可以使用任何设置来控制输出 jpeg 像素的行为
  • 我应该使用 *image.RGBA 吗?输入图像是 *image.YCbCr?
// Open the input image file
inputFile, _ := os.Open("a.jpg")
defer inputFile.Close()

// Decode the input image
inputImage, _, _ := image.Decode(inputFile)

// Get the dimensions of the input image
width := inputImage.Bounds().Dx()
height := inputImage.Bounds().Dy()
subWidth := width / 4
subHeight := height / 4

// Create a new image
subImg := image.NewRGBA(image.Rect(0, 0, subWidth, subHeight))
draw.Draw(subImg, subImg.Bounds(), inputImage, image.Point{0, 0}, draw.Src)

// id want the hashes to be the same for read / write but they will always differ
hash1 := sha256.Sum256(imageToBytes(subImg))
fmt.Printf("<---OUT [%s] %x\n", filename, hash1)
jpg, _ := os.Create("mytest.jpg")
_ = jpeg.Encode(jpg, subImg, nil)
jpg.Close()

// upon reading it back in the pixels are ever so slightly diff
f, _ := os.Open("mytest.jpg")
img, _, _ := image.Decode(f)
jpg_input := image.NewRGBA(img.Bounds())
draw.Draw(jpg_input, img.Bounds(), img, image.Point{0, 0}, draw.Src)
hash2 := sha256.Sum256(imageToBytes(jpg_input))
fmt.Printf("--->IN  [%s] %x\n", filename, hash2)

            // real world use case is..
            // generate subtile of large image plus hash
            // if hash in a dbase
            //    pixel walk to see if hash collision occurred
            //    if pixels are different
            //       deal with it...
            ///   else
            //      object.filename = dbaseb.filename
            // else
            //     add filename to dbase with hash as the lookup
            //     write to jpeg to disk
image go jpeg
1个回答
0
投票

我可以使用它

output := new(bytes.Buffer)
_ = jpeg.Encode(output, subImg, nil)
hash := sha256.Sum256(output.Bytes())
// write it later when i want with...
jpg.Write(output.Bytes())
© www.soinside.com 2019 - 2024. All rights reserved.