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

How to set the DPI of an image before saving it? #2235

Closed
xYx-c opened this issue May 15, 2024 · 1 comment
Closed

How to set the DPI of an image before saving it? #2235

xYx-c opened this issue May 15, 2024 · 1 comment

Comments

@xYx-c
Copy link

xYx-c commented May 15, 2024

pub fn build_dpi_chunk(dpi: u32) -> Vec<u8> {
    let dpm = 39.370_08 * dpi as f32;
    let rounded_dpm = dpm.round() as u32;

    let mut data = Vec::new();
    data.extend_from_slice(&rounded_dpm.to_be_bytes());
    data.extend_from_slice(&rounded_dpm.to_be_bytes());

    data.push(1);
    data
}

pub fn png_with_dpi<P>(imgbuf: ImageBuffer<P, Vec<u8>>, dpi: u32) -> Result<ImageBuffer<P, Vec<u8>>, std::io::Error>
where
    P: Pixel<Subpixel = u8>,
{
    let (width, height) = imgbuf.dimensions();
    let mut encoder = png::Encoder::new(imgbuf.clone().into_raw(), width, height);

    match <P as Pixel>::CHANNEL_COUNT {
        4 => encoder.set_color(png::ColorType::Rgba),
        3 => encoder.set_color(png::ColorType::Rgb),
        _ => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Incorrect color channel count / format.",
            ))
        },
    }
    encoder.set_depth(png::BitDepth::Eight);
    encoder.set_compression(png::Compression::Best);
    let data = build_dpi_chunk(dpi);

    let mut writer = encoder.write_header()?;

    writer.write_chunk(png::chunk::pHYs, data.as_slice())?;
    writer.write_image_data(&imgbuf)?;


    Ok(imgbuf)
}

I have tried using like this but it doesn't work correctly.

@fintelia
Copy link
Contributor

Duplicate of image-rs/image-png#482

@fintelia fintelia marked this as a duplicate of image-rs/image-png#482 May 16, 2024
@fintelia fintelia closed this as not planned Won't fix, can't repro, duplicate, stale May 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants