Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Encoding and decoding images in Rust

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
NotificationsYou must be signed in to change notification settings

image-rs/image

Repository files navigation

crates.ioDocumentationBuild StatusGitter

Maintainers:@197g,@fintelia

How to contribute

An Image Processing Library

This crate provides basic image processing functions and methods for converting to and from various image formats.

All image processing functions provided operate on types that implement theGenericImageView andGenericImage traits and return anImageBuffer.

High level API

Load images using [ImageReader]:

use std::io::Cursor;use image::ImageReader;let img =ImageReader::open("myimage.png")?.decode()?;let img2 =ImageReader::new(Cursor::new(bytes)).with_guessed_format()?.decode()?;

And save them using [save] or [write_to] methods:

img.save("empty.jpg")?;letmut bytes:Vec<u8> =Vec::new();img2.write_to(&mutCursor::new(&mut bytes), image::ImageFormat::Png)?;

Supported Image Formats

With default features enabled,image provides implementations of many commonimage format encoders and decoders.

FormatDecodingEncoding
AVIFYes *Yes (lossy only)
BMPYesYes
DDSYes---
FarbfeldYesYes
GIFYesYes
HDRYesYes
ICOYesYes
JPEGYesYes
EXRYesYes
PNGYesYes
PNMYesYes
QOIYesYes
TGAYesYes
TIFFYesYes
WebPYesYes (lossless only)
  • * Requires theavif-native feature, uses the libdav1d C library.

Image Types

This crate provides a number of different types for representing images.Individual pixels within images are indexed with (0,0) at the top left corner.

An image parameterised by its Pixel type, represented by a width and height anda vector of pixels. It provides direct access to its pixels and implements theGenericImageView andGenericImage traits.

ADynamicImage is an enumeration over all supportedImageBuffer<P> types.Its exact image type is determined at runtime. It is the type returned whenopening an image. For convenienceDynamicImage reimplements all imageprocessing functions.

Traits that provide methods for inspecting (GenericImageView) and manipulating (GenericImage) images, parameterised over the image's pixel type.

A view into another image, delimited by the coordinates of a rectangle.The coordinates given set the position of the top left corner of the rectangle.This is used to perform image processing functions on a subregion of an image.

All image format decoders implement theImageDecoder trait which providebasic methods for getting image metadata and decoding images. Some formatsadditionally provideImageDecoderRect implementations which allow fordecoding only part of an image at once.

The most important methods for decoders are...

  • dimensions: Return a tuple containing the width and height of the image.
  • color_type: Return the color type of the image data produced by this decoder.
  • read_image: Decode the entire image into a slice of bytes.

Pixels

image provides the following pixel types:

  • Rgb: RGB pixel
  • Rgba: RGB with alpha (RGBA pixel)
  • Luma: Grayscale pixel
  • LumaA: Grayscale with alpha

All pixels are parameterised by their component type.

Image Processing Functions

These are the functions defined in theimageops module. All functions operate on types that implement theGenericImage trait.Note that some of the functions are very slow in debug mode. Make sure to use release mode if you experience any performance issues.

  • blur: Performs a Gaussian blur on the supplied image.
  • brighten: Brighten the supplied image.
  • huerotate: Hue rotate the supplied image by degrees.
  • contrast: Adjust the contrast of the supplied image.
  • crop: Return a mutable view into an image.
  • filter3x3: Perform a 3x3 box filter on the supplied image.
  • flip_horizontal: Flip an image horizontally.
  • flip_vertical: Flip an image vertically.
  • grayscale: Convert the supplied image to grayscale.
  • invert: Invert each pixel within the supplied image This function operates in place.
  • resize: Resize the supplied image to the specified dimensions.
  • rotate180: Rotate an image 180 degrees clockwise.
  • rotate270: Rotate an image 270 degrees clockwise.
  • rotate90: Rotate an image 90 degrees clockwise.
  • unsharpen: Performs an unsharpen mask on the supplied image.

For more options, see theimageproc crate.

Examples

Opening and Saving Images

image provides theopen function for opening images from a path. The imageformat is determined from the path's file extension. Anio module provides areader which offer some more control.

use image::GenericImageView;// Use the open function to load an image from a Path.// `open` returns a `DynamicImage` on success.let img = image::open("tests/images/jpg/progressive/cat.jpg").unwrap();// The dimensions method returns the images width and height.println!("dimensions {:?}", img.dimensions());// The color method returns the image's `ColorType`.println!("{:?}", img.color());// Write the contents of this image to the Writer in PNG format.img.save("test.png").unwrap();

Generating Fractals

//! An example of generating julia fractals.let imgx =800;let imgy =800;let scalex =3.0 / imgxasf32;let scaley =3.0 / imgyasf32;// Create a new ImgBuf with width: imgx and height: imgyletmut imgbuf = image::ImageBuffer::new(imgx, imgy);// Iterate over the coordinates and pixels of the imagefor(x, y, pixel)in imgbuf.enumerate_pixels_mut(){let r =(0.3* xasf32)asu8;let b =(0.3* yasf32)asu8;*pixel = image::Rgb([r,0, b]);}// A redundant loop to demonstrate reading image datafor xin0..imgx{for yin0..imgy{let cx = yasf32* scalex -1.5;let cy = xasf32* scaley -1.5;let c = num_complex::Complex::new(-0.4,0.6);letmut z = num_complex::Complex::new(cx, cy);letmut i =0;while i <255 && z.norm() <=2.0{            z = z* z + c;            i +=1;}let pixel = imgbuf.get_pixel_mut(x, y);let image::Rgb(data) =*pixel;*pixel = image::Rgb([data[0], iasu8, data[2]]);}}// Save the image as “fractal.png”, the format is deduced from the pathimgbuf.save("fractal.png").unwrap();

Example output:

A Julia Fractal, c: -0.4 + 0.6i

Writing raw buffers

If the high level interface is not needed because the image was obtained by other means,image provides the functionsave_buffer to save a buffer to a file.

let buffer:&[u8] =unimplemented!();// Generate the image data// Save the buffer as "image.png"image::save_buffer("image.png", buffer,800,600, image::ExtendedColorType::Rgb8).unwrap()

About

Encoding and decoding images in Rust

Topics

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp