diff --git a/internal/epub/filters/resize.go b/internal/epub/filters/resize.go new file mode 100644 index 0000000..c08a0e5 --- /dev/null +++ b/internal/epub/filters/resize.go @@ -0,0 +1,47 @@ +package filters + +import ( + "image" + "image/draw" + + "github.com/disintegration/gift" +) + +func Resize(viewWidth, viewHeight int, resampling gift.Resampling) gift.Filter { + return &resizeFilter{ + viewWidth, viewHeight, resampling, + } +} + +type resizeFilter struct { + viewWidth, viewHeight int + resampling gift.Resampling +} + +func (p *resizeFilter) Bounds(srcBounds image.Rectangle) image.Rectangle { + w, h := p.viewWidth, p.viewHeight + srcw, srch := srcBounds.Dx(), srcBounds.Dy() + + if w <= 0 || h <= 0 || srcw <= 0 || srch <= 0 { + return image.Rect(0, 0, 0, 0) + } + + wratio := float64(srcw) / float64(w) + hratio := float64(srch) / float64(h) + + var dstw, dsth int + if wratio > hratio { + dstw = w + dsth = int(float64(srch)/wratio + 0.5) + } else { + dsth = h + dstw = int(float64(srcw)/hratio + 0.5) + } + + return image.Rect(0, 0, dstw, dsth) +} + +func (p *resizeFilter) Draw(dst draw.Image, src image.Image, options *gift.Options) { + b := p.Bounds(src.Bounds()) + gift.Resize(b.Dx(), b.Dy(), p.resampling).Draw(dst, src, options) +} diff --git a/internal/epub/image_filters.go b/internal/epub/image_filters.go index 75c5127..8567872 100644 --- a/internal/epub/image_filters.go +++ b/internal/epub/image_filters.go @@ -19,7 +19,7 @@ func NewGift(options *ImageOptions) *gift.GIFT { g.Add(gift.Brightness(float32(options.Brightness))) } g.Add( - gift.ResizeToFit(options.ViewWidth, options.ViewHeight, gift.LanczosResampling), + filters.Resize(options.ViewWidth, options.ViewHeight, gift.LanczosResampling), filters.Pixel(), ) return g