kolesa-team / go-webp

Simple and fast webp library for golang
MIT License
225 stars 36 forks source link

Scale options requiring both X and Y #15

Closed neurosnap closed 2 years ago

neurosnap commented 2 years ago

Greetings!

Great project. I ran into an issue today using the scale option for decoding a webp image. Is it possible to only scale the X of an image and have Y scale to preserve aspect ratio?

NinoM4ster commented 2 years ago

you can use a basic function to calculate the Y by using the formula shown on this very handy website:

(original height / original width) x new width = new height

something like this should work:

func calculateResizeHeight(oldWidth, oldHeight, newWidth float64) int {
    return int((oldHeight / oldWidth) * newWidth)
}

// calculateResizeHeight(1600, 1200, 400) returns 300.
neurosnap commented 2 years ago

That's fine but how do I get the original width and height before I decode the byte string into an image.Image?

NinoM4ster commented 2 years ago

depending on your architecture you might be able to extract the image resolution from some metadata (stored in a database or something).

or you can get the width and height from the image.Image.

edit: read below.

lEx0 commented 2 years ago

If you need an image dimension without full image decoding, you can use GetFeatures method of the decoder https://github.com/kolesa-team/go-webp/blob/master/decoder/decoder.go#L105 This method returns bitstream Metadate of web image