Skip to content

A fast, helpful, and open-source document parser

perf(ocr): render pages straight to RGB, drop redundant RGBA intermediate

jmho12d7f97d2901
diff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rs
index 12c428d..7df742e 100644
--- a/crates/liteparse/src/ocr_merge.rs
+++ b/crates/liteparse/src/ocr_merge.rs
@@ -3,7 +3,6 @@ use std::sync::Arc;
use crate::error::LiteParseError;
use crate::ocr::{OcrEngine, OcrOptions, OcrResult};
use crate::types::{Page, TextItem};
-use image::{ImageBuffer, Rgba};
use pdfium::Document;
/// Owned page bitmap prepared for OCR. Indices refer to positions in the `pages` slice.
@@ -60,14 +59,9 @@ pub(crate) fn render_pages_for_ocr(
let bitmap = page_obj.render(dpi)?;
let width = bitmap.width() as u32;
let height = bitmap.height() as u32;
- let rgba = bitmap.to_rgba();
-
- let img: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(width, height, rgba)
- .ok_or(LiteParseError::Other(
- "failed to create image buffer".into(),
- ))?;
- let rgb_img = image::DynamicImage::ImageRgba8(img).to_rgb8();
- let rgb_bytes = rgb_img.into_raw();
+ // RGB is what OCR consumes; converting straight from BGRA avoids an
+ // intermediate full-frame RGBA buffer per page.
+ let rgb_bytes = bitmap.to_rgb();
rendered.push(RenderedPage {
idx,
diff --git a/crates/pdfium/src/bitmap.rs b/crates/pdfium/src/bitmap.rs
index fc48ef5..6614fdc 100644
--- a/crates/pdfium/src/bitmap.rs
+++ b/crates/pdfium/src/bitmap.rs
@@ -92,6 +92,28 @@ impl Bitmap {
rgba
}
+
+ /// Convert the BGRA buffer to tightly-packed RGB in a new Vec, dropping the
+ /// alpha channel (pages render onto opaque white, so alpha is constant 255).
+ pub fn to_rgb(&self) -> Vec<u8> {
+ let width = self.width() as usize;
+ let height = self.height() as usize;
+ let stride = self.stride() as usize;
+ let src = self.buffer();
+ let mut rgb = Vec::with_capacity(width * height * 3);
+
+ for y in 0..height {
+ let row = &src[y * stride..y * stride + width * 4];
+ for pixel in row.chunks_exact(4) {
+ // BGRA -> RGB (drop A)
+ rgb.push(pixel[2]); // R
+ rgb.push(pixel[1]); // G
+ rgb.push(pixel[0]); // B
+ }
+ }
+
+ rgb
+ }
}
impl Drop for Bitmap {