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

Saving RgbaImage as JPEG is incorrect #2173

Closed
kmdreko opened this issue Mar 20, 2024 · 4 comments · Fixed by #2169
Closed

Saving RgbaImage as JPEG is incorrect #2173

kmdreko opened this issue Mar 20, 2024 · 4 comments · Fixed by #2169

Comments

@kmdreko
Copy link

kmdreko commented Mar 20, 2024

This happens in the following code:

[dependencies]
image = "0.25.0"
fn main() {
    image::open("input.jpg")
        .unwrap()
        .into_rgba8()
        .save("output.jpg")
        .unwrap();
}

Expected

I would've expected this to create roughly the output image as the input.

Actual behaviour

The output is a jumbled mess.

Reproduction steps

Here is the input.jpg file tested with:

input

And here is the output.jpg result:

output

Just now seeing it also looks different between image viewers: Windows Photos App vs Firefox.

Notes

This can be worked around by either:

  • downgrading to 0.24.9, or
  • using .into_rgb8() (no alpha channel), or
  • saving as .png
@vallentin
Copy link
Contributor

vallentin commented Mar 20, 2024

I was just writing an issue as well :)

For context, we're coming from this Stack Overflow question.

Here's a simpler example (not requiring any input). It breaks even when just creating a RgbaImage using from_pixel():

use image::{Rgb, RgbImage, Rgba, RgbaImage};

fn main() {
    let (w, h) = (64, 64);

    let img = RgbImage::from_pixel(w, h, Rgb([255, 0, 0]));
    img.save("rgb.jpg").unwrap();

    let img = RgbaImage::from_pixel(w, h, Rgba([255, 0, 0, 255]));
    img.save("rgba.jpg").unwrap();
}
version rgb.jpg rgba.jpg
0.24.9 rgb.jpg rgba.jpg
0.25.0 rgb.jpg rgba.jpg

@fintelia
Copy link
Contributor

JPEG doesn't support storing an alpha channel, so attempting to encode an RGBA image as JPEG should return an error. It is a bug that we silently produce a garbled image instead. (Silently dropping the alpha channel like in 0.24.9 is also a bug IMO).

I'd suggest using one of the workarounds suggested in the linked stack overflow answer: switch to a different format like PNG which actually supports alpha or manually remove the alpha channel via to_rgb8.

@yuanyan3060
Copy link
Contributor

yuanyan3060 commented Mar 22, 2024

#2169

fix rgba8 image jpeg encode bug

@mqudsi
Copy link

mqudsi commented Jun 16, 2024

Is there no way to statically prevent such code from compiling?

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

Successfully merging a pull request may close this issue.

5 participants