search
golang picture hideMay 16, 2023 am 09:13 AM

In modern society, digital technology continues to develop, and the issue of personal information protection in the online world has become increasingly important. In order to protect data privacy, people seek various encryption methods, among which picture hiding technology is a common encryption method. Golang, as an efficient programming language, can also be used to implement image hiding technology.

What is picture hiding?

The so-called picture hiding is to hide another picture or information in one picture, so that external users can only see the external picture and turn a blind eye to the hidden picture or information. This method can protect data privacy well and enhance data security to a certain extent.

Golang’s picture hiding principle

Golang, as an efficient programming language, is not only used for writing website back-end programs. Golang's image processing library "image" provides a wealth of image processing functions, which can perform various processing operations on images, such as image cropping, rotation, scaling, color adjustment, etc.

Picture hiding technology essentially embeds one picture into another picture. The embedding process is divided into two steps: first, convert the image to be hidden into a binary string, and then embed the binary string into the target image. When embedding, we can use the pixel data of the target image as a carrier and store the information to be hidden in certain bits in the pixel data in sequence. This hidden information can be another picture, text, audio, etc. When the recipient obtains the image, he or she can decrypt the information hidden in it.

Implementing picture hiding

We can use the image package provided by Golang to implement picture hiding. The following are the steps to implement:

Step 1: Read the target image

Use the Decode function of Golang's image package to decode the image file into an Image object in the Go language. In this example, we will use this function to read the target image.

func readImage(path string) (image.Image, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    defer f.Close()
    
    img, _, err := image.Decode(f)
    if err != nil {
        return nil, err
    }
    
    return img, nil
}

Step 2: Convert the image to be hidden into a binary string

We can use the ReadFile function in Golang's io/ioutil package to read the image to be hidden and convert it to Binary string.

func readData(path string) ([]byte, error) {
    data, err := ioutil.ReadFile(path)
    if err != nil {
        return nil, err
    }
    
    return data, nil
}

Step 3: Hide Data

In order to hide binary data, we need to create a new Image object and modify its pixel data. Since each pixel usually occupies four bytes (32 bits), we can use the last bit of each pixel to store data. For example, if the data to be hidden is 01100101, we can store it in the pixel of the target image. The specific method is to set the last bit of the pixel to 0 or 1 to store the data (because the last bit of a pixel is a bit, So one byte of data in 8 pixels can be stored).

func hideData(img image.Image, data []byte) (image.Image, error) {
    bounds := img.Bounds()
    
    newImg := image.NewRGBA(bounds)
    
    idx := 0    
    var r, g, b, a uint32
    
    for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
        for x := bounds.Min.X; x < bounds.Max.X; x++ {
            r, g, b, a = img.At(x, y).RGBA()
            if idx < len(data)*8 {
                bitIdx := idx % 8
                bits := uint32(data[idx/8])
                mask := uint32(0x00 << bitIdx)
                if bits&(1<<7-bitIdx) > 0 {
                    mask |= uint32(0x01 << bitIdx)
                }
                r = (r & 0xFFFE) | (mask & 0x01)
                g = (g & 0xFFFE) | ((mask >> 1) & 0x01)
                b = (b & 0xFFFE) | ((mask >> 2) & 0x01)
                a = (a & 0xFFFE) | ((mask >> 3) & 0x01)                
            }
            newImg.Set(x, y, color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)})
            idx++
        }
    }
    
    return newImg, nil
}

Step 4: Save the new image with hidden data

To save the new image with hidden data, use the Encode function of Golang's image package.

func saveImage(path string, img image.Image) error {
    f, err := os.Create(path)
    if err != nil {
        return err
    }
    defer f.Close()
    
    err = png.Encode(f, img)
    if err != nil {
        return err
    }
    
    return nil
}

Complete code:

package main

import (
    "fmt"
    "image"
    "image/color"
    "image/png"
    "io/ioutil"
    "os"
)

func main() {
    if len(os.Args) < 2 {
        fmt.Println("usage: go run main.go [filename]")
        return
    }
    
    filename := os.Args[1]
    dataPath := "data.png"
    outputPath := "output.png"
    
    fmt.Printf("Reading target image %s...
", filename)
    img, err := readImage(filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Printf("Reading data image %s...
", dataPath)
    data, err := readData(dataPath)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println("Hiding data...")
    newImg, err := hideData(img, data)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Printf("Saving image to %s...
", outputPath)
    err = saveImage(outputPath, newImg)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println("Done!")
}

func readImage(path string) (image.Image, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    defer f.Close()
    
    img, _, err := image.Decode(f)
    if err != nil {
        return nil, err
    }
    
    return img, nil
}

func readData(path string) ([]byte, error) {
    data, err := ioutil.ReadFile(path)
    if err != nil {
        return nil, err
    }
    
    return data, nil
}

func hideData(img image.Image, data []byte) (image.Image, error) {
    bounds := img.Bounds()
    
    newImg := image.NewRGBA(bounds)
    
    idx := 0    
    var r, g, b, a uint32
    
    for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
        for x := bounds.Min.X; x < bounds.Max.X; x++ {
            r, g, b, a = img.At(x, y).RGBA()
            if idx < len(data)*8 {
                bitIdx := idx % 8
                bits := uint32(data[idx/8])
                mask := uint32(0x00 << bitIdx)
                if bits&(1<<7-bitIdx) > 0 {
                    mask |= uint32(0x01 << bitIdx)
                }
                r = (r & 0xFFFE) | (mask & 0x01)
                g = (g & 0xFFFE) | ((mask >> 1) & 0x01)
                b = (b & 0xFFFE) | ((mask >> 2) & 0x01)
                a = (a & 0xFFFE) | ((mask >> 3) & 0x01)                
            }
            newImg.Set(x, y, color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)})
            idx++
        }
    }
    
    return newImg, nil
}

func saveImage(path string, img image.Image) error {
    f, err := os.Create(path)
    if err != nil {
        return err
    }
    defer f.Close()
    
    err = png.Encode(f, img)
    if err != nil {
        return err
    }
    
    return nil
}

The above are the steps and code for Golang to implement image hiding technology. It should be noted that this image hiding technology does not completely guarantee data security, it is just an encryption method. If data privacy is to be protected more strictly, other encryption methods need to be considered.

Summary

As an efficient programming language, Golang has excellent image processing capabilities. In this article, we use Golang to implement image hiding technology, which can ensure data privacy to a certain extent. It is worth noting that this technology cannot fully guarantee data security, so in practical applications, more encryption methods are needed to protect data privacy.

The above is the detailed content of golang picture hide. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Go language pack import: What is the difference between underscore and without underscore?Go language pack import: What is the difference between underscore and without underscore?Mar 03, 2025 pm 05:17 PM

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

How to implement short-term information transfer between pages in the Beego framework?How to implement short-term information transfer between pages in the Beego framework?Mar 03, 2025 pm 05:22 PM

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

How to convert MySQL query result List into a custom structure slice in Go language?How to convert MySQL query result List into a custom structure slice in Go language?Mar 03, 2025 pm 05:18 PM

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

How do I write mock objects and stubs for testing in Go?How do I write mock objects and stubs for testing in Go?Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go?How can I define custom type constraints for generics in Go?Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How to write files in Go language conveniently?How to write files in Go language conveniently?Mar 03, 2025 pm 05:15 PM

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

How do you write unit tests in Go?How do you write unit tests in Go?Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications?How can I use tracing tools to understand the execution flow of my Go applications?Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft