Skip to content

Instantly share code, notes, and snippets.

@d4hines
Created May 23, 2023 04:46
Show Gist options
  • Save d4hines/170de4ab5b71e3676e3c3cae83755e16 to your computer and use it in GitHub Desktop.
Save d4hines/170de4ab5b71e3676e3c3cae83755e16 to your computer and use it in GitHub Desktop.
turning tx log into gif
use clap::Parser;
use gif::{Encoder, Frame, Repeat};
use image::{Rgb};
use lib::message::{UserMessage, Content, PlacePixel};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Name of the person to greet
#[arg(index = 1)]
tx_log: String,
}
fn rgb_to_grayscale(Rgb(rgb): Rgb<u8>) -> Rgb<u8> {
let r = rgb[0] as f32;
let g = rgb[1] as f32;
let b = rgb[2] as f32;
let luminance = (0.299 * r + 0.587 * g + 0.114 * b).round() as u8;
Rgb([luminance, luminance, luminance])
}
fn main() {
let args = Args::parse();
// Open the file
let file = File::open(&args.tx_log).expect("Failed to open file");
let reader = BufReader::new(file);
let img = image::load_from_memory(include_bytes!("../white_image.png")).unwrap();
let mut img = img.to_rgb8();
let pk = "edpkteGd1TrY3sjERp7Jqfi56DyQXTrwkXnT5wQupf1do7pRsoP1sQ";
let target: lib::public_key::PublicKey = lib::public_key::PublicKey::from_b58(pk).unwrap();
let mut frames = Vec::new();
let mut i = 0;
// Iterate through each line
for line in reader.lines() {
// Process each line here
match line {
Ok(line_contents) => {
println!("processing line {}", i);
let tx: UserMessage = serde_json_wasm::from_str(line_contents.as_str()).unwrap();
let Content::PlacePixel(PlacePixel { x, y, color }) = tx.inner().content;
let color = Rgb([color[0], color[1], color[2]]);
let color = if target.eq(tx.public_key()) {
color
} else {
rgb_to_grayscale(color)
};
img.put_pixel(x, y, color);
let frame = Frame::from_rgb_speed(1024, 1024, img.as_raw(), 10);
frames.push(frame);
i = i + 1;
if i > 20 { break; }
}
Err(err) => {
eprintln!("Error reading line: {}", err);
// Handle the error appropriately
}
}
}
// Create a GIF encoder
let path = PathBuf::from(format!("./{}.gif", pk));
let file = File::create(path).unwrap();
let mut encoder = Encoder::new(file, 1024, 1024, &[]).unwrap();
encoder.set_repeat(Repeat::Infinite).unwrap();
// Write the frames to the GIF
for frame in frames {
encoder.write_frame(&frame).unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment