Skip to content

Instantly share code, notes, and snippets.

@nathamanath
Last active November 17, 2016 14:52
Show Gist options
  • Save nathamanath/a5bda4bdbd07e579188f to your computer and use it in GitHub Desktop.
Save nathamanath/a5bda4bdbd07e579188f to your computer and use it in GitHub Desktop.
rust image to data uri
extern crate rustc_serialize;
extern crate regex;
use rustc_serialize::base64::{ToBase64, MIME};
use rustc_serialize::hex::{ToHex};
use std::path::Path;
use std::env;
use std::fs::File;
use std::io::Read;
use regex::Regex;
fn main() {
if let Some(path) = env::args().nth(1) {
let path = Path::new(&path);
let mut file = File::open(&path).unwrap();
let mut buffer = Vec::new();
let _out = file.read_to_end(&mut buffer);
let b64 = buffer.to_base64(MIME);
let hex = buffer.to_hex();
println!("data:image/{};base64,{}", get_type(&hex), b64);
} else {
panic!("You must provide a file path");
}
}
fn get_type(file: &str) -> &str {
if Regex::new(r"^ffd8ffe0").unwrap().is_match(file) { "jpg" }
else if Regex::new(r"^89504e47").unwrap().is_match(file){ "png" }
else if Regex::new(r"^47494638").unwrap().is_match(file){ "gif" }
else { panic!("invalid file") }
}
@nathamanath
Copy link
Author

my first experiment with rust... convert image into data uri

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment