Home Backend Development Golang Golang image manipulation: how to mirror, rotate and flip images

Golang image manipulation: how to mirror, rotate and flip images

Aug 25, 2023 pm 10:31 PM
golang mirror Picture manipulation

Golang image manipulation: how to mirror, rotate and flip images

Golang image manipulation: How to mirror, rotate and flip images

1. Introduction
Image processing is something we often encounter in many development scenarios One of the requirements. In Golang, we can use the image package to operate and process images. This article will focus on how to use Golang to mirror, rotate and flip images, and provide corresponding code examples.

2. Mirror operation
Mirroring a picture is to change the left and right layout of the picture. In Golang, you can use the Flip function of the draw package to implement mirroring operations.

The following is a sample code to mirror and save images.

package main

import (
    "image"
    "image/draw"
    "image/jpeg"
    "os"
)

func main() {
    // 打开图片文件
    file, err := os.Open("input.jpg")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // 解码图片
    img, _, err := image.Decode(file)
    if err != nil {
        panic(err)
    }

    // 创建一个新的画布
    flipImg := image.NewRGBA(img.Bounds())

    // 镜像操作
    draw.Draw(flipImg, flipImg.Bounds(), img, img.Bounds().Min, draw.FlipHorizontal)

    // 创建输出文件
    output, err := os.Create("output_flip.jpg")
    if err != nil {
        panic(err)
    }
    defer output.Close()

    // 保存为JPEG格式图片
    jpeg.Encode(output, flipImg, nil)
}

3. Rotation operation
Rotating the picture is to change the direction and angle of the picture. In Golang, you can use the Rotate function of the draw package to implement rotation operations.

The following is a sample code to rotate the image 90 degrees clockwise and save it.

package main

import (
    "image"
    "image/draw"
    "image/jpeg"
    "os"
)

func main() {
    // 打开图片文件
    file, err := os.Open("input.jpg")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // 解码图片
    img, _, err := image.Decode(file)
    if err != nil {
        panic(err)
    }

    // 创建一个新的画布,大小为旋转后的尺寸
    rotateImg := image.NewRGBA(image.Rect(0, 0, img.Bounds().Dy(), img.Bounds().Dx()))

    // 旋转操作
    draw.Draw(rotateImg, rotateImg.Bounds(), img, img.Bounds().Min, draw.Rotate90)

    // 创建输出文件
    output, err := os.Create("output_rotate.jpg")
    if err != nil {
        panic(err)
    }
    defer output.Close()

    // 保存为JPEG格式图片
    jpeg.Encode(output, rotateImg, nil)
}

4. Flip operation
Flip operation on a picture is to change the top and bottom layout of the picture. In Golang, you can use the Flip function of the draw package to implement the flip operation.

The following is a sample code to flip the image and save it.

package main

import (
    "image"
    "image/draw"
    "image/jpeg"
    "os"
)

func main() {
    // 打开图片文件
    file, err := os.Open("input.jpg")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // 解码图片
    img, _, err := image.Decode(file)
    if err != nil {
        panic(err)
    }

    // 创建一个新的画布
    flipImg := image.NewRGBA(img.Bounds())

    // 翻转操作
    draw.Draw(flipImg, flipImg.Bounds(), img, img.Bounds().Min, draw.FlipVertical)

    // 创建输出文件
    output, err := os.Create("output_flip.jpg")
    if err != nil {
        panic(err)
    }
    defer output.Close()

    // 保存为JPEG格式图片
    jpeg.Encode(output, flipImg, nil)
}

In the above code example, we use the related functions of the image package to operate images. Among them, the image.Decode function is used to decode the image file and create an image object. Before operating, we first create a new canvas object (that is, create a new image object), and then use the functions of the draw package to perform operations such as mirroring, rotation, and flipping. Finally, use the Encode function of the jpeg package to save the processed image in JPEG format.

5. Summary
Through the introduction and code examples of this article, we have learned how to use Golang to mirror, rotate and flip images. In actual development, we can perform corresponding image processing operations according to specific needs to meet the needs of the project. At the same time, we can also combine with other image processing libraries, such as resize, crop, etc., to further complete more complex image operations.

I hope this article can be helpful to everyone in Golang image processing!

The above is the detailed content of Golang image manipulation: how to mirror, rotate and flip images. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1510
276
Golang vs. Python: The Pros and Cons Golang vs. Python: The Pros and Cons Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Strategies for Integrating Golang Services with Existing Python Infrastructure Strategies for Integrating Golang Services with Existing Python Infrastructure Jul 02, 2025 pm 04:39 PM

TointegrateGolangserviceswithexistingPythoninfrastructure,useRESTAPIsorgRPCforinter-servicecommunication,allowingGoandPythonappstointeractseamlesslythroughstandardizedprotocols.1.UseRESTAPIs(viaframeworkslikeGininGoandFlaskinPython)orgRPC(withProtoco

Best practices and tips for reducing Docker image volume Best practices and tips for reducing Docker image volume May 19, 2025 pm 08:42 PM

Methods to reduce the volume of Docker image include: 1. Use .dockerignore files to exclude unnecessary files; 2. Select a streamlined basic image, such as the alpine version; 3. Optimize Dockerfile, merge RUN commands and use the --no-cache option; 4. Use multi-stage construction to copy only the files that are needed in the end; 5. Manage dependent versions and regularly clean up dependencies that are no longer used. These methods not only reduce the image volume, but also improve the application startup speed and operation efficiency.

Golang's security settings on Debian Golang's security settings on Debian May 16, 2025 pm 01:15 PM

When setting up a Golang environment on Debian, it is crucial to ensure system security. Here are some key security setup steps and suggestions to help you build a secure Golang development environment: Security setup steps System update: Make sure your system is up to date before installing Golang. Update the system package list and installed packages with the following command: sudoaptupdatesudoaptupgrade-y Firewall Configuration: Install and configure a firewall (such as iptables) to limit access to the system. Only necessary ports (such as HTTP, HTTPS, and SSH) are allowed. sudoaptininstalliptablessud

Understanding the Performance Differences Between Golang and Python for Web APIs Understanding the Performance Differences Between Golang and Python for Web APIs Jul 03, 2025 am 02:40 AM

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

How to configure Golang network parameters in Debian How to configure Golang network parameters in Debian May 16, 2025 pm 01:06 PM

Adjusting Golang's network parameters in Debian system can be achieved in many ways. The following are several feasible methods: Method 1: Temporarily set environment variables by setting environment variables: Enter the following command in the terminal to temporarily set environment variables, and this setting is only valid in the current session. exportGODEBUG="gctrace=1netdns=go" where gctrace=1 will activate garbage collection tracking, and netdns=go will make Go use its own DNS resolver instead of the system default. Set environment variables permanently: add the above command to your shell configuration file, such as ~/.bashrc or ~/.profile

How to build a Golang environment on Debian How to build a Golang environment on Debian May 16, 2025 pm 12:51 PM

To build a Golang environment on the Debian system, you can follow the following steps: 1. Update the system package list First, make sure that your system package list is the latest: sudoaptupdate2. The official repository for installing GolangDebian provides Golang installation packages. You can use the following command to install: sudoaptinstallgolang-go3. Verify that after the installation is completed, you can verify that Golang is successfully installed through the following command: If the installation is successful, you will see an output similar to the following: governversiongo1.20.3linux/amd644. Set environment change

How to create a Dockerfile for a basic Golang application? How to create a Dockerfile for a basic Golang application? Jun 25, 2025 pm 04:48 PM

To write a Dockerfile for basic Golang applications, you need to understand three core steps: selecting a suitable image, building an application, and packaging the operating environment. 1. Use multi-stage construction to reduce volume. In the first stage, use golang:1.21 image to compile and generate executable files. In the second stage, only copy the compilation results and run them. 2. Set CGO_ENABLED=0 to avoid C library dependencies, unify the working directory such as /app and use the COPY instruction to copy the code. It is recommended to cooperate with .dockerignore to exclude irrelevant files; 3. Specify specific Go versions such as golang:1.21 instead of latest to ensure the controllable version and improve CI/CD consistency and compatibility.

See all articles