Golang Imaging Library for Image Decoding and Encoding

Author

Reads 170

AI Graphic Imaging
Credit: pexels.com, AI Graphic Imaging

The Go image library is a powerful tool for image decoding and encoding in Golang. It provides a simple and efficient way to work with images.

One of the key features of the Go image library is its ability to decode and encode images in various formats, including JPEG, PNG, and GIF. This makes it a versatile tool for a wide range of applications.

The library's decoding functionality allows developers to read image files and access their pixel data, while the encoding functionality enables them to create new images from scratch. This can be particularly useful for tasks such as image processing and manipulation.

With the Go image library, developers can easily work with images in Golang, making it a valuable addition to any project.

Here's an interesting read: Golang Get Image Metadata

Readers also liked: Golang Htmx

Image Operations

=====================================

The Go imaging package provides an array of image operations that can be performed on images. These include resize, enlarge, crop, rotate, flip, and flop.

Credit: youtube.com, Golang Image Processing Part 1 - Resize image using Go Imaging package

You can use the resize operation to change the size of an image. This can be done using various resampling filters, including Lanczos, CatmullRom, and MitchellNetravali. The choice of filter depends on the desired level of quality and speed.

Here are some of the most notable resampling filters and their characteristics:

The imaging package also supports image rotation, flipping, and flopping. The rotate operation can be performed with auto-rotate based on EXIF orientation.

Decode

The Decode function is a crucial part of image operations. It reads an image from a file or stream, r. This is an essential step in processing and analyzing images.

In the example, the Decode function is used to read an image from the file or stream, r. This function is used to convert the image data into a format that can be processed by the program.

The Decode function is a fundamental building block of image operations.

Explore further: Golang Read Image File

Layering Images on Base

Close-up of a layered shot drink in a glass, with sharp focus and blurred background.
Credit: pexels.com, Close-up of a layered shot drink in a glass, with sharp focus and blurred background.

Layering images on a base layer can be a bit tricky, but it's actually quite straightforward. You can use the draw package in Go to compose images over a background image.

To put multiple images over the base layer, you can loop the draw.Draw() function. This allows you to match the number of images you want to put over the base layer.

Remember to set the position (offset) of each image so they produce an aesthetic combination. You can use an array of images as input, with the higher index over the lower ones.

Take a look at this: How to Add Pic to Html

Clone

The Clone function is a powerful tool in image operations. It returns a copy of the given image, allowing you to work with a duplicate without affecting the original.

This is especially useful when you need to experiment with different edits on a photo without risking the original. You can clone the image, make changes, and then discard the copy when you're done.

Image Adjustments

Credit: youtube.com, Dynamic Image Resizing: Workhorse PoC / Golang

Image adjustments in golang imaging can be a breeze. The imaging package provides basic image processing functions, including resize, rotate, crop, and brightness/contrast adjustments.

You can adjust the saturation of an image using the AdjustSaturation function, which changes the saturation using a percentage parameter. The percentage must be in the range (-100, 100), where 0 gives the original image, 100 doubles the saturation for each pixel, and -100 zeros the saturation for each pixel, resulting in a grayscale image.

The AdjustBrightness function also uses a percentage parameter to change the brightness of an image. The percentage must be in the range (-100, 100), where 0 gives the original image, -100 gives a solid black image, and 100 gives a solid white image.

Broaden your view: Gcloud Api Using Golang

Adjust Saturation

Adjusting the saturation of an image can completely transform its mood and atmosphere. The AdjustSaturation function, introduced in inv1.6.0, allows you to achieve this with ease.

The percentage parameter determines the extent of the saturation change, and it must be within the range of -100 to 100.

Beautiful sunrise over a tranquil lake in Reit im Winkl, Bavaria, with mountain reflections.
Credit: pexels.com, Beautiful sunrise over a tranquil lake in Reit im Winkl, Bavaria, with mountain reflections.

Setting the percentage to 0 returns the image to its original state. I've found this to be particularly useful when I need to make other adjustments without affecting the saturation.

A percentage of 100 doubles the saturation value of each pixel, resulting in a more vibrant and intense image. This can be great for creative projects where you want to add some extra pop.

On the other hand, a percentage of -100 zeroes out the saturation value, effectively turning the image into a grayscale. This can be useful for creating a moody or atmospheric effect.

AdjustBrightness

Adjusting the brightness of an image can make a huge difference in its overall look and feel. You can use the AdjustBrightness function to change the brightness of an image using a percentage parameter.

The percentage must be in the range (-100, 100). This means you can darken or lighten the image to your liking. For example, a percentage of 0 will give you the original image, while -100 will give you a solid black image.

Credit: youtube.com, How to adjust brightness and contrast - Easy image enhancements (lesson 2)

If you want to make an image brighter, you can use a percentage of 100, which will give you a solid white image. This is a great way to add some extra brightness to an image that's looking a bit dull.

Here's a quick rundown of what you can expect from the AdjustBrightness function:

Image Filters

Image filters are a crucial aspect of image processing in GoLang's imaging package. They allow you to manipulate images in various ways, including resizing, rotating, and applying effects.

One of the most notable image filters is the resampling filter, which is used for resizing images. The imaging package supports various resampling filters, including Lanczos, CatmullRom, MitchellNetravali, Linear, Box, and NearestNeighbor.

The choice of resampling filter depends on the desired outcome. For example, Lanczos is a high-quality resampling filter that yields sharp results, while CatmullRom is a sharp cubic filter that is faster than Lanczos while providing similar results.

For another approach, see: Install Golang Package

Dramatic view from a Paris cathedral rooftop featuring a stone gargoyle overlooking historic architecture.
Credit: pexels.com, Dramatic view from a Paris cathedral rooftop featuring a stone gargoyle overlooking historic architecture.

Here's a comparison of some of the supported resampling filters:

The imaging package also supports custom filters using the ResampleFilter struct. This allows you to create your own filters using a combination of different filter types.

In addition to resampling filters, the imaging package also supports other types of image filters, including blur and convolution filters. The Blur function produces a blurred version of the image using a Gaussian function, while the Convolve3x3 and Convolve5x5 functions convolve the image with a specified 3x3 or 5x5 convolution kernel, respectively.

The imaging package provides a range of options for customizing the behavior of these filters, including the ability to specify the sigma parameter for the Blur function and the convolution kernel for the Convolve3x3 and Convolve5x5 functions.

You might enjoy: Golang Package Alias

Image Transformations

You can flip an image horizontally with the FlipH function, which flips the image from left to right and returns the transformed image.

The FlipV function is used to flip an image vertically, from top to bottom, and also returns the transformed image.

Credit: youtube.com, Image Processing in Go - CEO, SP Digital

Rotating an image is also possible, with the Rotate function rotating the image by a given angle counter-clockwise, and the Rotate270, Rotate90 functions rotating the image 270 and 90 degrees counter-clockwise respectively.

These rotation functions return the transformed image.

Here's a list of available image transformation functions:

These functions are all part of the imaging package and can be used to manipulate images in various ways.

Image Resizing and Cropping

Image resizing and cropping are essential image manipulation functions that can be achieved using the Go imaging package. The package supports various resampling filters, including Lanczos, CatmullRom, MitchellNetravali, Linear, Box, and NearestNeighbor.

You can resize an image using the Resize function, which takes the width and height as input and returns the transformed image. If one of the dimensions is 0, the image aspect ratio is preserved. The package also supports zooming and thumbnail creation, which can be achieved using the Thumbnail function.

Broaden your view: Golang Package

Credit: youtube.com, Build Image Crop Functionality | Golang, MySQL, Godotenv | GoGeek.dev

The imaging package provides several cropping functions, including Crop, CropAnchor, and CropCenter. These functions allow you to cut out a rectangular region from the image using the specified bounds, anchor point, or center of the image.

Here's a comparison of the resampling filters, listed from faster (lower quality) to slower (higher quality):

The supported resampling filters can be used to achieve high-quality results, and the package also supports custom filters using the ResampleFilter struct. The imaging package is based on the standard Go image package and works best along with it.

Image Format and Quality

Image quality is crucial for JPEG images, where a higher quality setting results in a better image.

The default JPEG quality is 95, which is a good starting point. However, you can adjust this setting to suit your needs, with a range of 1 to 100 inclusive.

To set the JPEG quality, you can use the JPEGQuality function, which returns an EncodeOption. This function allows you to specify the desired quality level, from 1 to 100.

For your interest: Setting up Golang

Encode

Credit: youtube.com, Image File Formats Explained: JPEG, PNG, GIF & More! | Which to Choose?

The Encode function is a powerful tool for saving images in various formats. It allows you to write an image to a writer in the specified format, including JPEG, PNG, GIF, TIFF, or BMP.

With Encode, you can save images with varying levels of compression. For instance, the PNGCompressionLevel function returns an EncodeOption that sets the compression level of the PNG-encoded image, with a default level of png.DefaultCompression.

You can also use Encode to save images with specific quality settings. The JPEGQuality function returns an EncodeOption that sets the output JPEG quality, ranging from 1 to 100 inclusive, with higher values indicating better quality. The default JPEG quality is 95.

When working with GIFs, the GIFDrawer function returns an EncodeOption that sets the drawer used to convert the source image to the desired palette of the GIF-encoded image. This is a useful feature for creating GIFs with specific color palettes.

Format from Extension

Credit: youtube.com, Explaining Image File Formats

You can use the FormatFromExtension function to parse the image format from the filename extension. This function is available in version 1.5.0 or later.

It supports formats like jpg, jpeg, png, gif, tif, and tiff. These are common image formats that you might encounter.

The function is useful when you know the filename extension but not the specific format. For example, if you have a file with a .jpg extension, you can use FormatFromExtension to determine that it's a JPEG format.

The supported formats include both lowercase and uppercase extensions, so you can use either "jpg" or "JPG" and get the same result.

GIF and Image Processing

GIFDrawer is a useful function that returns an EncodeOption, which sets the drawer used to convert the source image to the desired palette of the GIF-encoded image.

This is particularly useful for creating GIFs with specific color palettes.

GIFDrawer was added in version 1.4.0, making it a relatively new addition to the GoLang imaging package.

The image processing functions provided by the package, such as resizing and rotating images, accept any image type that implements the image.Image interface as an input.

These functions return a new image of *image.NRGBA type, which is a 32-bit RGBA color with non-premultiplied alpha.

GIFDrawer Inv 1.4.0

Back view anonymous female in gray hoodie looking at image on netbook screen and sitting at desk with takeaway coffee
Credit: pexels.com, Back view anonymous female in gray hoodie looking at image on netbook screen and sitting at desk with takeaway coffee

GIFDrawer Inv 1.4.0 is a significant update that brings a new feature to the table. The GIFDrawer returns an EncodeOption that sets the drawer used to convert the source image to the desired palette of the GIF-encoded image.

With GIFDrawer, you can now have more control over the image conversion process. This feature is especially useful when working with images that have complex palettes.

The GIFDrawer feature is available from version 1.4.0 onwards. This means that if you're using an older version, you'll need to upgrade to take advantage of this new feature.

GIFDrawer is a powerful tool for image processing, allowing you to fine-tune the palette of your GIF-encoded images.

Consider reading: Linode Images

GIF Quantizer v1.4.0

In version 1.4.0, GIFQuantizer was added to the library, allowing you to set the quantizer used to produce a palette of the GIF-encoded image.

The quantizer is a crucial aspect of GIF encoding, as it determines the number of colors used in the image. It can range from a simple dithering algorithm to a more complex one like Floyd-Steinberg.

Credit: youtube.com, How GIF Works | GIF Compression Explained In 3 Minutes

GIFQuantizer returns an EncodeOption that sets the quantizer, giving you fine-grained control over the encoding process. This allows you to optimize the image for specific use cases, such as web graphics or animations.

The default quantizer is not specified in the documentation, so you'll need to experiment with different options to find the one that works best for your needs.

Image Saving and Loading

Saving an image with Go is a straightforward process. You can use the `Save` function, which saves the image to a file with the specified filename. The format is determined from the filename extension.

The supported formats include "jpg" (or "jpeg"), "png", "tif" (or "tiff"), and "bmp". You can choose one of these formats based on your needs.

Save

The Save function is a powerful tool for saving images to file. It's determined by the filename extension.

Supported formats include "jpg" (or "jpeg"), "png", "tif" (or "tiff"), and "bmp". These are the most common image file types you'll encounter.

To save an image, simply use the Save function with the desired filename. The format will be automatically detected based on the extension.

For example, if you want to save an image as a JPEG, name your file with a ".jpg" or ".jpeg" extension. It's as simple as that!

Source Files

Computer Program Language Text
Credit: pexels.com, Computer Program Language Text

When saving an image, the source file format is crucial. It determines how the image data is stored and retrieved.

For example, JPEG files use a lossy compression algorithm, which discards some image data to reduce file size. This can result in a lower quality image.

PNG files, on the other hand, use a lossless compression algorithm, which preserves all image data. This makes PNG files ideal for images with text or graphics.

The source file format also affects the image's color depth and resolution. For instance, a 24-bit JPEG file can display over 16 million colors, whereas an 8-bit PNG file is limited to 256 colors.

In some cases, the source file format may not be compatible with the image loading library being used. This can result in errors or corrupted images.

To avoid these issues, it's essential to choose the right source file format for the job.

Image Examples and Usage

You can find usage examples in the documentation for the full list of supported functions.

Credit: youtube.com, Gophercises #19 - Building Images (png & svg)

The imaging package supports image resizing using various resampling filters. These filters include Lanczos, CatmullRom, MitchellNetravali, Linear, Box, NearestNeighbor, and more.

The most notable resampling filters are Lanczos, CatmullRom, and MitchellNetravali, which produce high-quality results, but at different speeds.

Here's a comparison of the resizing results using different filters:

The Sigma parameter allows you to control the strength of the blurring effect in the Sharpen function.

The imaging package also supports sRGB/Linear color space conversions and different output image types, such as 16 bits per channel.

You can use the imaging package to resize, rotate, flip, crop, and more, making it a great tool for image manipulation.

Image Properties and Orientation

AutoOrientation is a feature that returns a DecodeOption, which sets the auto-orientation mode. This mode transforms the image after decoding according to the EXIF orientation tag, if present.

The auto-orientation mode is disabled by default. However, you can enable it to automatically adjust the image orientation based on the EXIF tag.

Expand your knowledge: Golang Mode

Credit: youtube.com, Optimizing Image Resolution in Go for Web Uploads

Some image operations also support auto-rotate and auto-flip based on EXIF metadata. These operations include Rotate and Flip.

Here's a list of image operations that support EXIF metadata:

  • Rotate
  • Flip
  • Format conversion
  • EXIF metadata

The imaging package provides basic image manipulation functions, including resize, rotate, flip, and crop. It works best when used along with the standard Go image package.

Rosemary Boyer

Writer

Rosemary Boyer is a skilled writer with a passion for crafting engaging and informative content. With a focus on technical and educational topics, she has established herself as a reliable voice in the industry. Her writing has been featured in a variety of publications, covering subjects such as CSS Precedence, where she breaks down complex concepts into clear and concise language.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.