比较Golang中的base64图像字符串 [英] Comparing base64 image strings in Golang

查看:776
本文介绍了比较Golang中的base64图像字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务,可以比较两个以base64编码的图像字符串

I have a service that compares two base64 encoded image strings

我的最初尝试显示,在这种情况下,实际图像(JPG)相同(大小,分辨率,尺寸等)时,元数据存在差异.

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
}

推荐答案

感知哈希是一个用于计算一个phash;基于视觉特征的图像哈希. github.com/carlogit/phash 是一个golang实现.它具有创建和比较两个散列以给出距离"的功能,指示两个图像的相异程度.

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: 0

distance: 2

distance: 2

distance: 32

distance: 32

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/carlogit/phash"
)

func main() {
    if len(os.Args) < 3 {
        log.Fatalf("usage: %s <ImageFileA> <ImageFileB>\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
}

这篇关于比较Golang中的base64图像字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆