Skip to content

Commit

Permalink
Inplace decoding of lossless RGBA images (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
fintelia authored May 27, 2024
1 parent c7e2e5b commit 768b16b
Show file tree
Hide file tree
Showing 4 changed files with 410 additions and 528 deletions.
20 changes: 8 additions & 12 deletions src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,16 +608,16 @@ impl<R: Read + Seek> WebPDecoder<R> {
self.animation = saved;
result?;
} else if let Some(range) = self.chunks.get(&WebPRiffChunk::VP8L) {
let mut frame = LosslessDecoder::new(range_reader(&mut self.r, range.clone())?);
let frame = frame.decode_frame(None)?;
if u32::from(frame.width) != self.width || u32::from(frame.height) != self.height {
return Err(DecodingError::InconsistentImageSizes);
}
let mut decoder = LosslessDecoder::new(range_reader(&mut self.r, range.clone())?);

if self.has_alpha {
frame.fill_rgba(buf);
decoder.decode_frame(self.width, self.height, false, buf)?;
} else {
frame.fill_rgb(buf);
let mut data = vec![0; self.width as usize * self.height as usize * 4];
decoder.decode_frame(self.width, self.height, false, &mut data)?;
for (rgba_val, chunk) in data.chunks_exact(4).zip(buf.chunks_exact_mut(3)) {
chunk.copy_from_slice(&rgba_val[..3]);
}
}
} else {
let range = self
Expand Down Expand Up @@ -748,12 +748,8 @@ impl<R: Read + Seek> WebPDecoder<R> {
WebPRiffChunk::VP8L => {
let reader = (&mut self.r).take(chunk_size);
let mut lossless_decoder = LosslessDecoder::new(reader);
let frame = lossless_decoder.decode_frame(None)?;
if frame.width as u32 != frame_width || frame.height as u32 != frame_height {
return Err(DecodingError::InconsistentImageSizes);
}
let mut rgba_frame = vec![0; frame_width as usize * frame_height as usize * 4];
frame.fill_rgba(&mut rgba_frame);
lossless_decoder.decode_frame(frame_width, frame_height, false, &mut rgba_frame)?;
(rgba_frame, true)
}
WebPRiffChunk::ALPH => {
Expand Down
12 changes: 8 additions & 4 deletions src/extended.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,15 @@ pub(crate) fn read_alpha_chunk<R: Read>(

let data = if lossless_compression {
let mut decoder = LosslessDecoder::new(reader);
let frame = decoder.decode_frame(Some((width, height)))?;

let mut data = vec![0u8; usize::from(width) * usize::from(height)];
frame.fill_green(&mut data);
data
let mut data = vec![0; usize::from(width) * usize::from(height) * 4];
decoder.decode_frame(width as u32, height as u32, true, &mut data)?;

let mut green = vec![0; usize::from(width) * usize::from(height)];
for (rgba_val, green_val) in data.chunks_exact(4).zip(green.iter_mut()) {
*green_val = rgba_val[1];
}
green
} else {
let mut framedata = vec![0; width as usize * height as usize];
reader.read_exact(&mut framedata)?;
Expand Down
Loading

0 comments on commit 768b16b

Please sign in to comment.