1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
extern crate image;
use std::path::Path;
use image::{
GenericImage,
DynamicImage,
ImageBuffer,
Rgba
};
#[test]
fn it_works() {
let buffer = [0x00_u8];
let out = write_to_file(&buffer, "test.jpg".to_string());
let ref mut pout = &Path::new("test.png");
let _ = out.save(pout).unwrap();
let out_buf = read_from_file("test.png".to_string());
assert_eq!(0 as u8, *out_buf.get(0).unwrap());
}
pub fn write_to_file(input: &[u8], filename: String) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
let img = image::open(&Path::new(&filename)).unwrap();
return write_to_image(input, img);
}
pub fn read_from_file(filename: String) -> Vec<u8> {
let img = image::open(&Path::new(&filename)).unwrap().to_rgba();
return read_from_image(img);
}
pub fn write_to_image(input: &[u8], img: DynamicImage) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
let (width, height) = img.dimensions();
let bytes = width * height;
if input.len() > bytes as usize{
panic!("Input is too large for image size");
}
let mut out = ImageBuffer::new(width, height);
for (x, y, pixel) in img.pixels() {
let mut tmp_pixel = pixel;
if x+y < input.len() as u32{
tmp_pixel.data[3] = input[(x+y) as usize];
}
out.put_pixel(x, y, tmp_pixel);
}
return out;
}
pub fn read_from_image(img: ImageBuffer<Rgba<u8>, Vec<u8>>) -> Vec<u8> {
let mut out: Vec<u8> = Vec::new();
for (x, y, pixel) in img.enumerate_pixels() {
out.push(pixel.data[3]);
}
return out;
}