Browse Source

Fixed edge case with the end of the file; more correct algorithm to extract PNGs, though it might give you worse results in some cases

master
parent
commit
1510aac743
  1. 2
      Cargo.lock
  2. 2
      Cargo.toml
  3. 214
      src/main.rs

2
Cargo.lock generated

@ -4,4 +4,4 @@ version = 3
[[package]] [[package]]
name = "pngrip" name = "pngrip"
version = "0.1.2" version = "0.1.3"

2
Cargo.toml

@ -1,6 +1,6 @@
[package] [package]
name = "pngrip" name = "pngrip"
version = "0.1.2" version = "0.1.3"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

214
src/main.rs

@ -13,115 +13,78 @@ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR I
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::Path; use std::path::Path;
/// extracts png images from file that path points to, saving every image to destination directory. #[derive(Debug)]
/// If an error occurs - returns immediately. struct Position {
fn rip_png(path: &Path, destination: &Path) { start: usize,
let png_identifier: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10]; end: usize,
let iend_identifier: [u8; 4] = [73, 69, 78, 68];
let filename;
match path.file_name() {
Some(name) => {
filename = String::from(name.to_string_lossy());
}
None => {
eprintln!("[ERROR] Could not get filename from \"{}\"", path.display());
return;
}
} }
println!("[INFO] Ripping PNGs from \"{}\"...", filename); // Reads data from specified start_index position,
// if valid png bytes were found - returns exact positions of an image
fn rip_png(data: &[u8], start_index: usize) -> Option<Position> {
const PNG_IDENTIFIER: [u8; 8] = [0x89, 0x50, 0x4E, 0x47, 0xD, 0xA, 0x1A, 0xA];
const PNG_END_IDENTIFIER: [u8; 8] = [0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82];
let mut file; if data.len() < PNG_IDENTIFIER.len() + PNG_END_IDENTIFIER.len() ||
match std::fs::File::open(path) { start_index + PNG_IDENTIFIER.len() + PNG_END_IDENTIFIER.len() > data.len() {
Ok(f) => { return None;
file = f;
} }
Err(e) => { let mut position: Position = Position{
eprintln!("[ERROR] On opening \"{}\": {}", filename, e); start: usize::MAX,
return; end: usize::MAX,
} };
}
let mut file_bytes: Vec<u8> = Vec::new(); for i in start_index..data.len() {
match file.read_to_end(&mut file_bytes) { // start index
Ok(_) => {} if i < data.len() - PNG_IDENTIFIER.len() && position.start == usize::MAX {
Err(e) => { if data[i..i + PNG_IDENTIFIER.len()] == PNG_IDENTIFIER {
eprintln!("[ERROR] On reading \"{}\": {}", filename, e); position.start = i;
return;
} }
} }
let mut image_count: u64 = 0; // end index
if i <= data.len() - PNG_END_IDENTIFIER.len() && position.end == usize::MAX {
let mut start_pos: usize = 0; if data[i..i + PNG_END_IDENTIFIER.len()] == PNG_END_IDENTIFIER {
let mut last_pos: usize = 0; position.end = i + PNG_END_IDENTIFIER.len();
let mut end_pos: usize = 0;
for i in 0..file_bytes.len()-iend_identifier.len() {
if i < file_bytes.len() - png_identifier.len() {
if file_bytes[i..i + png_identifier.len()] == png_identifier {
start_pos = i;
}
} }
if file_bytes[i..i + iend_identifier.len()] == iend_identifier {
end_pos = i + iend_identifier.len();
} }
if start_pos < end_pos && start_pos != last_pos { if position.start != usize::MAX && position.end != usize::MAX {
last_pos = start_pos; break;
image_count += 1;
let mut ripped_image_file;
let ripped_image_filename = format!("{}_{}.png", filename, image_count);
match std::fs::File::create(destination.join(&ripped_image_filename)) {
Ok(f) => {
ripped_image_file = f;
}
Err(e) => {
eprintln!("[ERROR] On creating \"{}\": {}", &ripped_image_filename, e);
return;
} }
} }
match ripped_image_file.write_all(&mut file_bytes[start_pos..end_pos]) { if position.start == usize::MAX || position.end == usize::MAX || position.end <= position.start {
Ok(_) => {} return None;
Err(e) => {
eprintln!("[ERROR] On writing to \"{}\": {}", ripped_image_filename, e);
return;
}
}
}
} }
println!("[INFO] Ripped {} images from \"{}\" in total", image_count, filename); return Some(position);
} }
fn main() { fn main() {
let args: Vec<String> = std::env::args().collect(); let args: Vec<String> = std::env::args().collect();
if args.len() < 3 { if args.len() < 3 {
println!("pngrip v0.1.2\nUSAGE: pngrip [DESTINATION] [FILES]..."); println!("pngrip v0.1.3\nUSAGE: pngrip [DESTINATION] [FILES]...");
std::process::exit(0); std::process::exit(0);
} }
// handle DESTINATION argument // handle DESTINATION argument
let mut destination = Path::new(&args[1]); let mut destination_path = Path::new(&args[1]);
match destination.exists() { match destination_path.exists() {
true => { true => {
if !destination.is_dir() { if !destination_path.is_dir() {
// destination exists, but is not a directory // destination exists, but is not a directory
destination = Path::new("."); destination_path = Path::new(".");
eprintln!("[ERROR] Provided destination path is not a directory ! Saving to current directory..."); eprintln!("[ERROR] Provided destination path is not a directory ! Saving to current directory...");
} }
} }
false => { false => {
// destination does not exist, create it // destination does not exist, create it
match std::fs::create_dir_all(&destination) { match std::fs::create_dir_all(&destination_path) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
destination = Path::new("."); destination_path = Path::new(".");
eprintln!("[ERROR] Could not create destination directory: {}. Saving to current directory...", e); eprintln!("[ERROR] Could not create destination directory: {}. Saving to current directory...", e);
} }
} }
@ -130,14 +93,107 @@ fn main() {
// go through all files and try to rip all PNGs // go through all files and try to rip all PNGs
for file_to_check in &args[2..] { for file_path_index in 0..args[2..].len() {
let path = Path::new(file_to_check); let file_path: &Path = Path::new(&args[file_path_index]);
if !path.exists() {
eprintln!("[ERROR] \"{}\" does not exist", file_to_check); print!("\n");
if !file_path.exists() {
println!("[ERROR] \"{}\" does not exist", file_path.display());
continue;
}
// get file's metadata
let file_metadata: std::fs::Metadata;
match std::fs::metadata(file_path) {
Ok(metadata) => {
file_metadata = metadata;
}
Err(error) => {
println!("[ERROR] Could not retrieve \"{}\"'s metadata: {}", file_path.display(), error);
continue;
}
}
// skip directories
if file_metadata.is_dir() {
println!("[INFO] Skipping directory \"{}\"...", file_path.display());
continue;
}
println!("[INFO] Working with \"{}\"...", file_path.display());
let mut file_contents: Vec<u8> = Vec::with_capacity(file_metadata.len() as usize);
let mut file_handle: std::fs::File;
match std::fs::File::open(file_path) {
Ok(f_handle) => {
file_handle = f_handle;
}
Err(error) => {
println!("[ERROR] Could not open \"{}\": {}", file_path.display(), error);
continue; continue;
} }
}
match file_handle.read_to_end(&mut file_contents) {
Ok(_) => {}
Err(error) => {
println!("[ERROR] Error reading \"{}\": {}", file_path.display(), error);
}
}
rip_png(path, destination); let mut positions: Vec<Position> = Vec::new();
let mut cursor_index: usize = 0;
while (cursor_index as u64) < file_metadata.len() {
match rip_png(&file_contents, cursor_index) {
Some(pos) => {
cursor_index = pos.end;
positions.push(pos);
}
None => {
break;
}
}
}
let file_name: String;
match file_path.file_name() {
Some(fname) => {
file_name = String::from(fname.to_string_lossy());
}
None => {
eprintln!("[ERROR] Could not retrieve this file's name");
continue;
}
}
for position_index in 0..positions.len() {
let output_file_name: String = format!("{}_{}.png", file_name, position_index);
let mut output_file: std::fs::File;
match std::fs::File::create(destination_path.join(&output_file_name)) {
Ok(f) => {
output_file = f;
}
Err(error) => {
eprintln!("[ERROR] Error creating output file: {}", error);
continue;
}
}
match output_file.write(&file_contents[positions[position_index].start..positions[position_index].end]) {
Ok(_) => {
println!("[INFO] Outputted \"{}\"", output_file_name);
}
Err(error) => {
eprintln!("[ERROR] Could not write PNG to the output file: {}", error);
continue;
}
}
}
} }
} }
Loading…
Cancel
Save