golang中base64编码_在Golang中比较base64图像字符串

博客围绕比较两个Base64编码的图像字符串展开,指出初始比较时存在元数据差异,即便实际图像相同。介绍了去除动态元数据以比较图像视觉方面的方法,还给出了Golang实现Base64编码的代码,以及使用Perceptual Hash库计算图像哈希值进行比较的方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have a service that compares two base64 encoded image strings

My initial attempt revealed that there is differences in metadata while the actual image (JPG) in this case is identical (size,resolution,dimensions,etc).

Is there a way to strip away much of the dynamic metadata so that I can just compare the visual aspect of the image?

Currently, I am using the following...

package converter

import (

"bufio"

"encoding/base64"

"log"

"os"

)

func Base64(path string) (string, error) {

imgFile, err := os.Open(path)

if err != nil {

log.Fatalln(err)

}

defer imgFile.Close()

// create a new buffer base on file size

fInfo, _ := imgFile.Stat()

var size int64 = fInfo.Size()

buf := make([]byte, size)

// read file content into buffer

fReader := bufio.NewReader(imgFile)

fReader.Read(buf)

// convert the buffer bytes to base64 string - use buf.Bytes() for new image

imgBase64Str := base64.StdEncoding.EncodeToString(buf)

return imgBase64Str,nil

}

解决方案

Perceptual Hash is a library to calculate a phash; a hash of an image based on visual characteristics. github.com/carlogit/phash is a golang implementation. It has functions to create and compare two hashes to give a 'distance' indicating how dissimilar two images are.

Out of interest I gave it a try, it's simple to use and effective with some test images. For example:

distance: 0

distance: 2

distance: 32

package main

import (

"fmt"

"log"

"os"

"github.com/carlogit/phash"

)

func main() {

if len(os.Args) < 3 {

log.Fatalf("usage: %s \n", os.Args[0])

}

a := hash(os.Args[1])

b := hash(os.Args[2])

distance := phash.GetDistance(a, b)

fmt.Printf("distance: %d\n", distance)

}

//hash returns a phash of the image

func hash(filename string) string {

img, err := os.Open(filename)

if err != nil {

log.Fatal(err)

}

defer img.Close()

ahash, err := phash.GetHash(img)

if err != nil {

log.Fatal(err)

}

return ahash

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值