png_to_jpeg/png_to_jpeg.rs
1use libvips::{ops, VipsApp, VipsImage};
2use std::env;
3use std::path::Path;
4
5// Load a JPEG file, transform and convert it to PNG
6// Use the following cargo command to run this example
7// cargo run --example jpeg_to_png
8
9fn main() {
10 // this initializes the libvips library. it has to live as long as the application lives (or as long as you want to use the library within your app)
11 // you can't have multiple objects of this type and when it is dropped it will call the libvips functions to free all internal structures.
12 let app = VipsApp::new(
13 "Test Libvips",
14 false,
15 )
16 .expect("Cannot initialize libvips");
17
18 //set number of threads in libvips's threadpool
19 app.concurrency_set(2);
20 let cargo_toml_dir = env::current_dir()
21 .expect("Where is my Cargo.toml file?")
22 .display()
23 .to_string();
24 let image_path = Path::new("examples/test.png")
25 .display()
26 .to_string();
27
28 // loads an image from file
29 let image = VipsImage::new_from_file(&format!(
30 "{}/{}",
31 cargo_toml_dir, image_path
32 ))
33 .unwrap();
34
35 // will resize the image and return a new instance.
36 // libvips works most of the time with immutable objects, so it will return a new object
37 // the VipsImage struct implements Drop, which will free the memory
38 let resized = ops::resize(
39 &image,
40 0.5,
41 )
42 .unwrap();
43
44 //optional parameters
45 let options = ops::JpegsaveOptions {
46 q: 90,
47 background: vec![255.0],
48 interlace: true,
49 optimize_coding: true,
50 optimize_scans: true,
51 ..ops::JpegsaveOptions::default()
52 };
53
54 // alternatively you can use `jpegsave` that will use the default options
55 match ops::jpegsave_with_opts(
56 &resized,
57 &format!(
58 "{}/examples/{}",
59 cargo_toml_dir, "png_to_jpeg.jpg"
60 ),
61 &options,
62 ) {
63 Err(_) => println!(
64 "error: {}",
65 app.error_buffer()
66 .unwrap()
67 ),
68 Ok(_) => println!("png_to_jpeg.jpg was created within the examples directory!"),
69 }
70}