Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancements for PNG-BRUH Converter: Improved UX, Error Handling, and Unique Temp Files #12

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
214 changes: 90 additions & 124 deletions main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,121 +2,82 @@

use eframe::egui;
use egui_extras::RetainedImage;

extern crate css_color_parser;

use colors_transform::Rgb;
use image;
use image::GenericImageView;
use std::{
env,
fs::{self, OpenOptions},
io::Write,
path::PathBuf,
};

use skia_safe::{
AlphaType, Color4f, ColorType, EncodedImageFormat, ImageInfo, Paint, Rect, Surface,
};

use image::{self, GenericImageView};
use skia_safe::{AlphaType, Color4f, ColorType, EncodedImageFormat, ImageInfo, Paint, Rect, Surface};
use css_color_parser::Color as CssColor;
use uuid::Uuid;
use std::{env, fs, io::{self, Write}, path::PathBuf};

static TEMP_RESULT_PATH: &str = "temp.png";

fn vec_to_u32_ne(bytes: &[u8]) -> u32 {
let mut result = [0u8; 4];
result.copy_from_slice(bytes);
u32::from_ne_bytes(result)
/// Generates a unique temporary file path
fn generate_temp_file_path() -> PathBuf {
let uuid = Uuid::new_v4();
PathBuf::from(format!("temp_{}.png", uuid))
}

fn png_to_bruh(path: PathBuf) -> Result<(), std::io::Error> {
let img = image::open(&path).expect("File not found!");
let mut str = String::new();
/// Converts a PNG file to a `.bruh` format
fn png_to_bruh(path: PathBuf) -> io::Result<()> {
let img = image::open(&path).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid image file"))?;
let mut result = String::new();
let mut last_line = 0;

for pixel in img.pixels() {
let hex_color = Rgb::from(
pixel.2 .0[0] as f32,
pixel.2 .0[1] as f32,
pixel.2 .0[2] as f32,
)
let hex_color = Rgb::from(pixel.2 .0[0] as f32, pixel.2 .0[1] as f32, pixel.2 .0[2] as f32)
.to_css_hex_string();

if last_line != pixel.1 {
str.push_str("\n");
result.push('\n');
last_line = pixel.1;
}
str.push_str(&hex_color.replace("#", ""));
result.push_str(&hex_color.replace('#', ""));
}

if let Some(path_str) = &path.to_str() {
let height: u32 = img.height();
let width: u32 = img.width();

let height_bytes: [u8; 4] = height.to_ne_bytes();
let width_bytes: [u8; 4] = width.to_ne_bytes();
let path_to_bruh = path_str.replace(".png", ".bruh");

let mut file = OpenOptions::new()
.write(true)
.create(true)
.open(path_to_bruh)
.expect("Couldnt write");
let string_bytes: Vec<u8> = Vec::from(str.as_bytes());

file.write_all(&width_bytes).unwrap();
file.write_all(&height_bytes).unwrap();
file.write_all(&string_bytes).unwrap();
file.flush().unwrap();
} else {
println!("{}", "couldn't find")
}
let height = img.height();
let width = img.width();

Ok(())
}
let height_bytes = height.to_ne_bytes();
let width_bytes = width.to_ne_bytes();

fn bruh_to_png(path: PathBuf) -> (u32, u32) {
let mut contents: Vec<u8> = fs::read(&path).expect("Couldn't read file.");
let binding: Vec<_> = contents.drain(0..8).collect();
let path_to_bruh = path.with_extension("bruh");
let mut file = fs::File::create(&path_to_bruh)?;

let width = vec_to_u32_ne(&binding[0..4]);
let height = vec_to_u32_ne(&binding[4..8]);
file.write_all(&width_bytes)?;
file.write_all(&height_bytes)?;
file.write_all(result.as_bytes())?;

let sanitized_content = String::from_utf8_lossy(&contents).replace("\n", "");
println!("Successfully converted PNG to BRUH: {:?}", path_to_bruh);
Ok(())
}

let result: Vec<&str> = sanitized_content
.as_bytes()
.chunks(6)
.map(std::str::from_utf8)
.collect::<Result<_, _>>()
.expect("Invalid UTF-8 sequence in the input string");
/// Converts a `.bruh` file to a PNG and returns its dimensions
fn bruh_to_png(path: PathBuf) -> io::Result<(u32, u32, PathBuf)> {
let contents = fs::read(&path)?;
let (width_bytes, height_bytes) = contents.split_at(4);
let width = u32::from_ne_bytes(width_bytes.try_into().unwrap());
let height = u32::from_ne_bytes(height_bytes[0..4].try_into().unwrap());

let color_data = &contents[8..];
let sanitized_content = String::from_utf8_lossy(color_data).replace("\n", "");
let colors: Vec<&str> = sanitized_content.as_bytes()
.chunks(6)
.map(std::str::from_utf8)
.collect::<Result<_, _>>()
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid BRUH file format"))?;

let info = ImageInfo::new(
(width as i32, height as i32),
ColorType::RGBA8888,
AlphaType::Opaque,
None,
ColorType::RGBA8888,
AlphaType::Opaque,
None,
);

let mut surface = Surface::new_raster(&info, None, None).unwrap();
let canvas = surface.canvas();

for (i, color) in result.iter().enumerate() {
let hex = "#".to_owned() + color;

let parsed_color = hex
.parse::<CssColor>()
.expect("Failed to convert Hex to RGB");
let color4f = Color4f::new(
parsed_color.r as f32,
parsed_color.g as f32,
parsed_color.b as f32,
0.004 as f32,
);
for (i, color) in colors.iter().enumerate() {
let hex = format!("#{}", color);
let parsed_color = hex.parse::<CssColor>().map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid color"))?;
let color4f = Color4f::new(parsed_color.r as f32, parsed_color.g as f32, parsed_color.b as f32, 1.0);
let paint = Paint::new(color4f, None);
if i == 0 {
println!("{:?}", paint)
}

let x = i % width as usize;
let y = i / width as usize;

Expand All @@ -125,59 +86,64 @@ fn bruh_to_png(path: PathBuf) -> (u32, u32) {
}

let image = surface.image_snapshot();

let temp_file_path = generate_temp_file_path();
if let Some(data) = image.encode(None, EncodedImageFormat::PNG, 100) {
fs::write(TEMP_RESULT_PATH, &*data).expect("Failed to write image data to file");
fs::write(&temp_file_path, &*data)?;
}

return (width, height);
Ok((width, height, temp_file_path))
}

fn main() -> Result<(), eframe::Error> {
/// Main application
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = env::args().collect();
let file_path: PathBuf = (&args[1]).into();

if &args[1] == "compile" {
if args.len() < 3 {
panic!("Secondary argument ('path') not provided. Example: `cargo run compile ~/image.png`")
}

let path: PathBuf = (&args[2]).into();
if args.len() < 2 {
println!("Usage:");
println!(" To compile PNG to BRUH: `cargo run compile <image.png>`");
println!(" To preview BRUH file: `cargo run <file.bruh>`");
return Ok(());
}

match png_to_bruh(path) {
Ok(()) => println!("{}", "Successfully converted PNG to BRUH"),
Err(_) => println!("{}", "Failed to convert PNG to BRUH"),
match args[1].as_str() {
"compile" => {
if args.len() < 3 {
println!("Please provide a valid PNG file path.");
return Ok(());
}
png_to_bruh(PathBuf::from(&args[2]))?;
}
_ => {
let (width, height, temp_file) = bruh_to_png(PathBuf::from(&args[1]))?;
let options = eframe::NativeOptions {
resizable: false,
initial_window_size: Some(egui::vec2(width as f32, height as f32)),
..Default::default()
};
if let Err(e) = eframe::run_native(
"Image preview",
options,
Box::new(|_cc| Box::new(ImagePreview::new(temp_file))),
) {
eprintln!("An error occurred: {}", e);
}

Ok(())
} else {
let (width, height) = bruh_to_png(file_path);
println!("{} {}", width, height);
let options = eframe::NativeOptions {
resizable: false,
initial_window_size: Some(egui::vec2(width as f32, height as f32)),
..Default::default()
};

eframe::run_native(
"Image preview",
options,
Box::new(|_cc| Box::<ImagePreview>::default()),
)
}
}
Ok(())
}

/// Image preview struct for eframe
struct ImagePreview {
image: RetainedImage,
}

impl Default for ImagePreview {
fn default() -> Self {
let image_data = std::fs::read(TEMP_RESULT_PATH).expect("Failed to read image file");

fs::remove_file(TEMP_RESULT_PATH).expect("File delete failed on TEMP_RESULT_PATH");

impl ImagePreview {
fn new(temp_file: PathBuf) -> Self {
let image_data = fs::read(&temp_file).expect("Failed to read temp image file");
fs::remove_file(temp_file).expect("Failed to delete temp file");
Self {
image: RetainedImage::from_image_bytes(TEMP_RESULT_PATH, &image_data).unwrap(),
image: RetainedImage::from_image_bytes("temp_image", &image_data).unwrap(),
}
}
}
Expand Down