https://github.com/andriykalashnykov/wasm-image-editor
rust + wasm
https://github.com/andriykalashnykov/wasm-image-editor
rust rust-lang wasm
Last synced: 8 months ago
JSON representation
rust + wasm
- Host: GitHub
- URL: https://github.com/andriykalashnykov/wasm-image-editor
- Owner: AndriyKalashnykov
- License: mpl-2.0
- Created: 2023-07-27T13:33:34.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2023-07-27T13:36:42.000Z (about 2 years ago)
- Last Synced: 2025-02-24T06:49:54.942Z (8 months ago)
- Topics: rust, rust-lang, wasm
- Language: JavaScript
- Homepage:
- Size: 7.31 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# wasm-image-editor
Image Editor powered by WebAssembly and Rust.
| JavaScript | WebAssembly |
| --- | --- |
|  |  |## Pre-requisites
* [cargo-binstall](https://github.com/cargo-bins/cargo-binstall)
```bash
curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash
```
* [cargo-watch](https://github.com/watchexec/cargo-watch)
```bash
cargo binstall cargo-watch
```
* [cargo-server](https://github.com/raphamorim/cargo-server)
```bash
cargo binstall cargo-server
```## Try it
[Try it: https://raphamorim.io/wasm-image-editor](https://raphamorim.io/wasm-image-editor)
| Filter | WASM (best) | WASM (average) | JavaScript (best) |JavaScript (average) |
| --- | --- | --- | --- | --- |
| [Grayscale](#grayscale) | ~7ms | ~10ms | ~10ms | ~14ms |
| Sepia | WIP | WIP | WIP | WIP |Filter suggestion? Open an issue :)
## Grayscale
#### The Weighted Method:
```
Grayscale = 0.299R + 0.587G + 0.114B
```Example (rust with casting between f32 and u8):
```rust
let grayscale = ((pixels[i] as f32 * 0.3) + (pixels[i+1] as f32 * 0.59) + (pixels[i+2] as f32 * 0.11)) as u8;
```#### Average Method:
```
Grayscale = (R + G + B ) / 3
```Theoretically, the formula is 100% correct. But when writing code, you may encounter uint8 overflow error. The sum of R, G, and B is greater than 255. To avoid the exception, R, G, and B should be calculated, respectively.
```
Grayscale = R / 3 + G / 3 + B / 3
```#### Rust:
```rust
let pixels = unsafe { from_raw_parts_mut(data as *mut u8, len) };
let mut i = 0;
loop {
if i >= len - 1 {
break;
}let grayscale = (pixels[i] / 3) + (pixels[i + 1] / 3) + (pixels[i + 2] / 3);
pixels[i] = grayscale;
pixels[i + 1] = grayscale;
pixels[i + 2] = grayscale;
i += 4;
}
```#### Javascript:
```javascript
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const pixels = imageData.data;
for (var i = 0, n = pixels.length; i < n; i += 4) {
const grayscale = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
pixels[i] = grayscale;
pixels[i+1] = grayscale;
pixels[i+2] = grayscale;
}
```