golang 成像新手

我正在try 为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)

Go相关问答推荐

为什么我不能使用Docker从本地访问我的Gin应用程序?

错误&对象已被Golang在K8s操作符上修改

golang有int32溢出吗?

如何使用gopher-lua定义一个Lua函数,该函数有一个预定义的表作为param,Lua脚本可以在其中访问该函数中的表?

如何修复proxyconnect tcp:tls:第一条记录看起来不像tls握手

从带有嵌套括号的字符串中提取值

Golang和Gin web框架在router.Run()之后执行代码

如何测试光纤参数

我突然无法再将我的 GoLang 应用程序部署到 Google AppEngine

GoLang: gocui 边框 colored颜色

使用模拟在 golang 中测试我的界面.专门测试调用同级函数的 1 个函数

如何使用名称具有包名称的嵌套 struct 启动 go struct

也许在 golang 中包(字符串和字符串类型不匹配)

如何使用 go-playground/validator 编写 snake case 绑定标签?

如何使用 fyne Go 使用 canvas.NewText() 使文本可滚动

在恒等函数中将类型 T 转换为类型 U

如果服务器在客户端的 gRPC 中不可用,则等待的方法

为什么import和ImportSpec之间可以出现多行注释,而PackageName和ImportPath之间不能出现?

Go lang - 惯用的默认后备

Gorilla/Mux 和 Websocket 竞赛条件,这安全吗?