Native Tutorial¶
In this tutorial, we're going to write a program that resizes an image and applies a filter to it. You'll get a feel for how to use Photon, and will be able to build upon this to use Photon in your own projects.
Getting Started¶
Ensuring you have Rust installed, create a new Rust project:
cargo new photon-demo --bin
cd photon-demo
Once you've moved into the new directory, take a look at the source files generated.
Add Photon as A Dependency¶
Add Photon as a dependency to your project:
1 2 |
|
Your Cargo.toml should look like this:
Cargo.toml¶
1 2 3 4 5 6 7 8 9 10 |
|
Writing The Program¶
Next up, open your bin.rs
file. You'll find a sample function in there, remove that since we won't be using it.
Open An Image¶
To open an image:
bin.rs¶
1 2 3 4 5 6 |
|
Apply a Filter Effect¶
To apply a filter effect to the opened image, we need to pass in our image and a filter name.
1 |
|
Notice that we're passing a mutable reference to the image. This allows the function to modify the image, rather than return a new image. There are a variety of filter effects we can pass. Once you get the program compiled, try passing in "radio" instead of the filter above. For a full list, see the documentation.
Save To The Filesystem¶
Then, to write the image to the filesystem:
1 |
|
Notice here we're saving it as a JPG image, but we could also save it as a PNG or a different output format, by including a different file extension.
Get An Image¶
Next up, you'll need an image to work with. You can use an image from your own collection, or try out the images available at Unsplash, which are also available in the Public Domain.
Name it image.jpg
, and save it in the same directory as your rust project.
Final Program¶
The final code looks like this:
bin.rs¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Run The Code¶
To run the program in release mode, run:
cargo run --release
Warning
Make sure you run in release mode for optimum performance, by adding the --release flag to your command. Otherwise, performance will be greatly affected.
Bonus: Add Timing¶
If you'd like to find out how long it takes to process your image, you can add some code to capture this.
Add the time
dependency to your Cargo.toml:
Cargo.toml¶
[dependencies]
time="0.2.1"
Then in your code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Want More Examples?¶
To view more examples for native-use, check out the /examples
folder in Photon's repository. You'll find full instructions on how to run these in the README.
Working with the Web¶
If you'd like to get started with Photon for the web, see the accompanying web tutorial.