登录
首页 >  Golang >  Go问答

生成 JPEG 图像的一致哈希值,无需将其写入磁盘

来源:stackoverflow

时间:2024-02-08 12:24:20 341浏览 收藏

你在学习Golang相关的知识吗?本文《生成 JPEG 图像的一致哈希值,无需将其写入磁盘》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

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

正确答案


您可以使用哈希作为编写器的目标,并使用 io.MultiWriter 在写入文件时计算哈希:

hash:=sha256.New()
jpeg.Encode(io.MultiWriter(file,hash),img,nil)
hashValue:=hash.Sum(nil)

好了,本文到此结束,带大家了解了《生成 JPEG 图像的一致哈希值,无需将其写入磁盘》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>