mattes / epeg

Insanely fast JPEG/ JPG thumbnail scaling with the minimum fuss and CPU overhead. It makes use of libjpeg features of being able to load an image by only decoding the DCT coefficients needed to reconstruct an image of the size desired.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it possible to use this to crop to center and retain aspect ratio?

deweydb opened this issue · comments

I've got an input of files of various sizes, i want to create square thumbnails of all of them but retain aspect ratio and crop when necessary. Is this possible with epeg?

Short answer is yes. We use epeg for exactly that purpose. I can't give you the long answer at the moment since I'm on vacation but epeg can certainly do what you asked.

Actually, thinking about this some more, perhaps we had to add one extra step of our own to add letterboxing when necessary after epeg created the thumbnails. Sorry for the lack of specificity at the moment.

@Adam-VisualVocal would it be possible for you to post the long answer? I'm struggling to solve this exact problem.

This is how we do it.

  1. Open the source image file with epeg_file_open.
  2. Get the width and height of the source image file using epeg_size_get.
  3. Compute the scale factor required for your thumbnail with something like this:
    float scale = min(
        1.0f, // EPEG can't scale up so limit max scale to 1.0
        (float)thumbnailMaxWidth / (float)sourceWidth,
        (float)thumbnailMaxHeight / (float)sourceHeight));
  1. Use the scale to compute the aspect-ratio correct size of the thumbnail.
    int thumbnailWidth = RoundToInt(scale * sourceWidth);
    int thumbnailHeight = RoundToInt(scale * sourceHeight);
  1. Stuff the thumbnail width and height into epeg_decode_size_set.
  2. Set your output file name using epeg_file_output_set.
  3. Generate your thumbnail with epeg_encode.

This will give you a thumbnail with the same aspect ratio as the original source image whose width and height are no larger than thumbnailMaxWidth and thumbnailMaxHeight respectively.

If you want your thumbnail file to be padded with blank pixels to make it square then you'll have to add a few extra steps. For example, replace the last two steps with a call to epeg_pixels_get to get the uncompressed thumbnail pixels into memory. Then manually blit those pixels onto the center of a square, blank image and save that as your thumbnail.