在开发过程中,我们经常需要比较图像文件的相似度,以便进行图像识别、去重等操作。而生成图像的哈希值是一种常见的方法。通常,我们需要将图像写入磁盘,再读取出来进行哈希计算。然而,使用Golang编程语言,我们可以轻松地实现在生成jpeg图像的同时,直接计算出一致的哈希值,而无需写入磁盘。这为我们节省了时间和磁盘空间,提高了效率。本文将详细介绍如何在Golang中实现这一功能。
问题内容
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)
以上是Golang 为 jpeg 图像生成一致的哈希值,而无需写入磁盘的详细内容。更多信息请关注PHP中文网其他相关文章!

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

开发者应遵循以下最佳实践:1.谨慎管理goroutines以防止资源泄漏;2.使用通道进行同步,但避免过度使用;3.在并发程序中显式处理错误;4.了解GOMAXPROCS以优化性能。这些实践对于高效和稳健的软件开发至关重要,因为它们确保了资源的有效管理、同步的正确实现、错误的适当处理以及性能的优化,从而提升软件的效率和可维护性。

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

我们需要自定义错误类型,因为标准错误接口提供的信息有限,自定义类型能添加更多上下文和结构化信息。1)自定义错误类型能包含错误代码、位置、上下文数据等,2)提高调试效率和用户体验,3)但需注意其复杂性和维护成本。

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

禅工作室 13.0.1
功能强大的PHP集成开发环境

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

记事本++7.3.1
好用且免费的代码编辑器