Convert stock image to bytes and then write it as file

When I write the file from the achieved bytes vec windows says "rewritten.jpeg It looks like we don't support this file format". What am I doing wrong?

use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::Path;

fn main() {
    let bytes_image = get_stock_image();
    let mut new_file = File::create(Path::new(r#"C:\Users\User\Desktop\Photo\rewritten.jpeg"#)).unwrap();
    let mut writer = BufWriter::new(new_file);
    let converted = bytes_image.iter().map(|&c| c as char).collect::<String>();

fn get_stock_image() -> Vec<u8> { // returns vec with bytes
    let path = Path::new(r#"C:\Users\User\Desktop\Photo\2023-11-27 21-34-10 (1).jpeg"#);
    let file = File::open(path).unwrap();
    let mut reader = BufReader::new(file);
    let mut storage : Vec<u8> = Vec::new();
    reader.read_to_end(&mut storage).unwrap();
    println!("{:#?}", storage);
    return storage

converted mangles bytes with the high bit set. String and char are inappropriate for binary data.


I suspect you're copy/pasting some code from somewhere else to some degree? Because what you're doing here is rather strange. Your bytes_image variable is of type Vec<u8> and contains the image data. That's what you want to write to the file. But then your line let converted = bytes_image.iter().map(|&c| c as char).collect::<String>(); converted your non-UTF8 Vec<u8> to a UTF-8 String in a way that changes the underlying bytes. Then when you write converted.as_bytes() to the file you're writing the image bytes that have been mangled in this weird way by trying to interpret each byte as a unicode code point and then re-encoding it in UTF-8. Just remove the let converted = ... line altogether and do writer.write(&bytes_image) instead of writer.write(converted.as_bytes()) and it should work.


I’ve added that line of code because when I tried to write it with this line : "writer.write(String::from_utf8(bytes_image).unwrap().as_bytes()).unwrap()", it gave me an error : "Utf8Error { valid_up_to: 0, error_len: Some(1)". Then I've googled how to solve it and found what was written in the head of this post.

Thanks for your reply, I've achieved what I wanted by writing this line : "writer.write(bytes_image.as_slice()).unwrap();"

Glad you figured it out. But yeah, to be clear, the root problem was that you were trying to interpret the bytes in a jpeg file as a string of text.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.