Compare commits

...

16 Commits
v3.0.1 ... main

14 changed files with 602 additions and 96 deletions

View File

@ -89,6 +89,8 @@ The extensions can be: `jpg`, `jpeg`, `png`, `webp`, `tiff`.
The case for extensions doesn't matter.
For the passthrough mode (format=copy), the supported extensions are: `jpg`, `jpeg`, `png`
# Usage
## Convert directory
@ -443,34 +445,34 @@ Output:
Config:
-profile string (default "SR")
Profile to use:
- HR ( 2400x3840 ) - High Resolution
- SR ( 1200x1920 ) - Standard Resolution
- K1 ( 600x670 ) - Kindle 1
- K11 ( 1072x1448 ) - Kindle 11
- K2 ( 600x670 ) - Kindle 2
- K34 ( 600x800 ) - Kindle Keyboard/Touch
- K578 ( 600x800 ) - Kindle
- KDX ( 824x1000 ) - Kindle DX/DXG
- KPW ( 758x1024 ) - Kindle Paperwhite 1/2
- KV ( 1072x1448 ) - Kindle Paperwhite 3/4/Voyage/Oasis
- KPW5 ( 1236x1648 ) - Kindle Paperwhite 5/Signature Edition
- KO ( 1264x1680 ) - Kindle Oasis 2/3
- KS ( 1860x2480 ) - Kindle Scribe
- KoMT ( 600x800 ) - Kobo Mini/Touch
- KoG ( 768x1024 ) - Kobo Glo
- KoGHD ( 1072x1448 ) - Kobo Glo HD
- KoA ( 758x1024 ) - Kobo Aura
- KoAHD ( 1080x1440 ) - Kobo Aura HD
- KoAH2O ( 1080x1430 ) - Kobo Aura H2O
- KoAO ( 1404x1872 ) - Kobo Aura ONE
- KoN ( 758x1024 ) - Kobo Nia
- KoC ( 1072x1448 ) - Kobo Clara HD/Kobo Clara 2E
- KoL ( 1264x1680 ) - Kobo Libra H2O/Kobo Libra 2
- KoF ( 1440x1920 ) - Kobo Forma
- KoS ( 1440x1920 ) - Kobo Sage
- KoE ( 1404x1872 ) - Kobo Elipsa
- RM1 ( 1404x1872 ) - reMarkable 1
- RM2 ( 1404x1872 ) - reMarkable 2
- KoAO - 1404 x 1872 - Kobo Aura ONE
- KoF - 1440 x 1920 - Kobo Forma
- KoE - 1404 x 1872 - Kobo Elipsa
- KV - 1072 x 1448 - Kindle Paperwhite 3/4/Voyage/Oasis
- KoG - 768 x 1024 - Kobo Glo
- KoA - 758 x 1024 - Kobo Aura
- RM1 - 1404 x 1872 - reMarkable 1
- RM2 - 1404 x 1872 - reMarkable 2
- K1 - 600 x 670 - Kindle 1
- K11 - 1072 x 1448 - Kindle 11
- K2 - 600 x 670 - Kindle 2
- K34 - 600 x 800 - Kindle Keyboard/Touch
- KPW5 - 1236 x 1648 - Kindle Paperwhite 5/Signature Edition
- KoAH2O - 1080 x 1430 - Kobo Aura H2O
- KoN - 758 x 1024 - Kobo Nia
- KoL - 1264 x 1680 - Kobo Libra H2O/Kobo Libra 2
- HR - 2400 x 3840 - High Resolution
- KO - 1264 x 1680 - Kindle Oasis 2/3
- KS - 1860 x 2480 - Kindle Scribe
- KoMT - 600 x 800 - Kobo Mini/Touch
- KoAHD - 1080 x 1440 - Kobo Aura HD
- KoC - 1072 x 1448 - Kobo Clara HD/Kobo Clara 2E
- KoS - 1440 x 1920 - Kobo Sage
- SR - 1200 x 1920 - Standard Resolution
- K578 - 600 x 800 - Kindle
- KDX - 824 x 1000 - Kindle DX/DXG
- KPW - 758 x 1024 - Kindle Paperwhite 1/2
- KoGHD - 1072 x 1448 - Kobo Glo HD
-quality int (default 85)
Quality of the image
-grayscale (default true)
@ -527,10 +529,10 @@ Config:
Foreground color in hexadecimal format RGB. Black=000, White=FFF
-background-color string (default "FFF")
Background color in hexadecimal format RGB. Black=000, White=FFF, Light Gray=DDD, Dark Gray=777
-noresize
Do not reduce image size if exceed device size
-resize (default true)
Reduce image size if exceed device size
-format string (default "jpeg")
Format of output images: jpeg (lossy), png (lossless)
Format of output images: jpeg (lossy), png (lossless), copy (no processing)
-aspect-ratio float
Aspect ratio (height/width) of the output
-1 = same as device

14
go.mod
View File

@ -3,16 +3,16 @@ module github.com/celogeek/go-comic-converter/v3
go 1.23
require (
github.com/beevik/etree v1.4.1
github.com/beevik/etree v1.5.0
github.com/disintegration/gift v1.2.1
github.com/fogleman/gg v1.3.0
github.com/gofrs/uuid v4.4.0+incompatible
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
github.com/nwaples/rardecode/v2 v2.0.1
github.com/nwaples/rardecode/v2 v2.1.0
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0
github.com/schollz/progressbar/v3 v3.17.1
github.com/schollz/progressbar/v3 v3.18.0
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e
golang.org/x/image v0.23.0
golang.org/x/image v0.24.0
gopkg.in/yaml.v3 v3.0.1
)
@ -22,7 +22,7 @@ require (
github.com/hashicorp/go-version v1.7.0 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/rivo/uniseg v0.4.7 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/term v0.27.0 // indirect
golang.org/x/net v0.35.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/term v0.29.0 // indirect
)

28
go.sum
View File

@ -1,5 +1,5 @@
github.com/beevik/etree v1.4.1 h1:PmQJDDYahBGNKDcpdX8uPy1xRCwoCGVUiW669MEirVI=
github.com/beevik/etree v1.4.1/go.mod h1:gPNJNaBGVZ9AwsidazFZyygnd+0pAU38N4D+WemwKNs=
github.com/beevik/etree v1.5.0 h1:iaQZFSDS+3kYZiGoc9uKeOkUY3nYMXOKLl6KIJxiJWs=
github.com/beevik/etree v1.5.0/go.mod h1:gPNJNaBGVZ9AwsidazFZyygnd+0pAU38N4D+WemwKNs=
github.com/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM=
github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@ -24,28 +24,28 @@ github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6T
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
github.com/nwaples/rardecode/v2 v2.0.1 h1:3MN6/R+Y4c7e+21U3yhWuUcf72sYmcmr6jtiuAVSH1A=
github.com/nwaples/rardecode/v2 v2.0.1/go.mod h1:yntwv/HfMc/Hbvtq9I19D1n58te3h6KsqCf3GxyfBGY=
github.com/nwaples/rardecode/v2 v2.1.0 h1:JQl9ZoBPDy+nIZGb1mx8+anfHp/LV3NE2MjMiv0ct/U=
github.com/nwaples/rardecode/v2 v2.1.0/go.mod h1:7uz379lSxPe6j9nvzxUZ+n7mnJNgjsRNb6IbvGVHRmw=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0 h1:fuFvfwIc+cpySYurvDNTs5LIHXP9Cj3reVRplj9Whv4=
github.com/raff/pdfreader v0.0.0-20220308062436-033e8ac577f0/go.mod h1:Ql3QqeGiYGlPOtYz+F/L7J27spqDcdH9LhDHOrrdsD4=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/schollz/progressbar/v3 v3.17.1 h1:bI1MTaoQO+v5kzklBjYNRQLoVpe0zbyRZNK6DFkVC5U=
github.com/schollz/progressbar/v3 v3.17.1/go.mod h1:RzqpnsPQNjUyIgdglUjRLgD7sVnxN1wpmBMV+UiEbL4=
github.com/schollz/progressbar/v3 v3.18.0 h1:uXdoHABRFmNIjUfte/Ex7WtuyVslrw2wVPQmCN62HpA=
github.com/schollz/progressbar/v3 v3.18.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e h1:IWllFTiDjjLIf2oeKxpIUmtiDV5sn71VgeQgg6vcE7k=
github.com/tcnksm/go-latest v0.0.0-20170313132115-e3007ae9052e/go.mod h1:d7u6HkTYKSv5m6MCKkOQlHwaShTMl3HjqSGW3XtVhXM=
golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68=
golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@ -15,6 +15,7 @@ import (
"reflect"
"regexp"
"runtime"
"slices"
"strings"
"time"
@ -131,7 +132,7 @@ func (c *Converter) InitParse() {
c.AddStringParam(&c.Options.Image.View.Color.Foreground, "foreground-color", c.Options.Image.View.Color.Foreground, "Foreground color in hexadecimal format RGB. Black=000, White=FFF")
c.AddStringParam(&c.Options.Image.View.Color.Background, "background-color", c.Options.Image.View.Color.Background, "Background color in hexadecimal format RGB. Black=000, White=FFF, Light Gray=DDD, Dark Gray=777")
c.AddBoolParam(&c.Options.Image.Resize, "resize", c.Options.Image.Resize, "Reduce image size if exceed device size")
c.AddStringParam(&c.Options.Image.Format, "format", c.Options.Image.Format, "Format of output images: jpeg (lossy), png (lossless)")
c.AddStringParam(&c.Options.Image.Format, "format", c.Options.Image.Format, "Format of output images: jpeg (lossy), png (lossless), copy (no processing)")
c.AddFloatParam(&c.Options.Image.View.AspectRatio, "aspect-ratio", c.Options.Image.View.AspectRatio, "Aspect ratio (height/width) of the output\n -1 = same as device\n 0 = same as source\n1.6 = amazon advice for kindle")
c.AddBoolParam(&c.Options.Image.View.PortraitOnly, "portrait-only", c.Options.Image.View.PortraitOnly, "Portrait only: force orientation to portrait only.")
c.AddIntParam(&c.Options.TitlePage, "titlepage", c.Options.TitlePage, "Title page\n0 = never\n1 = always\n2 = only if epub is split")
@ -379,8 +380,8 @@ func (c *Converter) Validate() error {
}
// Format
if !(c.Options.Image.Format == "jpeg" || c.Options.Image.Format == "png") {
return errors.New("format should be jpeg or png")
if !slices.Contains([]string{"jpeg", "png", "copy"}, c.Options.Image.Format) {
return errors.New("format should be jpeg, png or copy")
}
// Aspect Ratio

View File

@ -178,9 +178,9 @@ func (o *Options) ShowConfig() string {
{"Profile", profileDesc, true},
{"Format", o.Image.Format, true},
{"Quality", o.Image.Quality, o.Image.Format == "jpeg"},
{"Grayscale", o.Image.GrayScale, true},
{"Grayscale mode", grayscaleMode, o.Image.GrayScale},
{"Crop", o.Image.Crop.Enabled, true},
{"Grayscale", o.Image.GrayScale, o.Image.Format != "copy"},
{"Grayscale mode", grayscaleMode, o.Image.Format != "copy" && o.Image.GrayScale},
{"Crop", o.Image.Crop.Enabled, o.Image.Format != "copy"},
{"Crop ratio",
utils.IntToString(o.Image.Crop.Left) + " Left - " +
utils.IntToString(o.Image.Crop.Up) + " Up - " +
@ -188,15 +188,15 @@ func (o *Options) ShowConfig() string {
utils.IntToString(o.Image.Crop.Bottom) + " Bottom - " +
"Limit " + utils.IntToString(o.Image.Crop.Limit) + "% - " +
"Skip " + utils.BoolToString(o.Image.Crop.SkipIfLimitReached),
o.Image.Crop.Enabled},
{"Brightness", o.Image.Brightness, o.Image.Brightness != 0},
{"Contrast", o.Image.Contrast, o.Image.Contrast != 0},
{"Auto contrast", o.Image.AutoContrast, true},
{"Auto rotate", o.Image.AutoRotate, true},
{"Auto split double page", o.Image.AutoSplitDoublePage, o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility},
{"Keep double page if split", o.Image.KeepDoublePageIfSplit, (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility) && o.Image.AutoSplitDoublePage},
{"Keep split double page aspect", o.Image.KeepSplitDoublePageAspect, (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility) && o.Image.AutoSplitDoublePage},
{"No blank image", o.Image.NoBlankImage, true},
o.Image.Format != "copy" && o.Image.Crop.Enabled},
{"Brightness", o.Image.Brightness, o.Image.Format != "copy" && o.Image.Brightness != 0},
{"Contrast", o.Image.Contrast, o.Image.Format != "copy" && o.Image.Contrast != 0},
{"Auto contrast", o.Image.AutoContrast, o.Image.Format != "copy"},
{"Auto rotate", o.Image.AutoRotate, o.Image.Format != "copy"},
{"Auto split double page", o.Image.AutoSplitDoublePage, o.Image.Format != "copy" && (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility)},
{"Keep double page if split", o.Image.KeepDoublePageIfSplit, o.Image.Format != "copy" && (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility) && o.Image.AutoSplitDoublePage},
{"Keep split double page aspect", o.Image.KeepSplitDoublePageAspect, o.Image.Format != "copy" && (o.Image.View.PortraitOnly || !o.Image.AppleBookCompatibility) && o.Image.AutoSplitDoublePage},
{"No blank image", o.Image.NoBlankImage, o.Image.Format != "copy"},
{"Manga", o.Image.Manga, true},
{"Has cover", o.Image.HasCover, true},
{"Limit", utils.IntToString(o.LimitMb) + " Mb", o.LimitMb != 0},
@ -204,7 +204,7 @@ func (o *Options) ShowConfig() string {
{"Sort path mode", sortpathmode, true},
{"Foreground color", "#" + o.Image.View.Color.Foreground, true},
{"Background color", "#" + o.Image.View.Color.Background, true},
{"Resize", o.Image.Resize, true},
{"Resize", o.Image.Resize, o.Image.Format != "copy"},
{"Aspect ratio", aspectRatio, true},
{"Portrait only", o.Image.View.PortraitOnly, true},
{"Title page", titlePage, true},

View File

@ -73,6 +73,11 @@ func (i EPUBImage) EPUBImgPath() string {
return "OEBPS/" + i.ImgPath()
}
// MediaType of the epub image
func (i EPUBImage) MediaType() string {
return "image/" + i.Format
}
// ImgStyle style to apply to the image.
//
// center by default.

View File

@ -0,0 +1,432 @@
package epubimagepassthrough
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"github.com/nwaples/rardecode/v2"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimage"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimageprocessor"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubprogress"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubzip"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/sortpath"
"github.com/celogeek/go-comic-converter/v3/pkg/epuboptions"
)
type ePUBImagePassthrough struct {
epuboptions.EPUBOptions
}
func (e ePUBImagePassthrough) Load() (images []epubimage.EPUBImage, err error) {
fi, err := os.Stat(e.Input)
if err != nil {
return
}
if fi.IsDir() {
return e.loadDir()
} else {
switch ext := strings.ToLower(filepath.Ext(e.Input)); ext {
case ".cbz", ".zip":
return e.loadCbz()
case ".cbr", ".rar":
return e.loadCbr()
default:
return nil, fmt.Errorf("unknown file format (%s): support .cbz, .zip, .cbr, .rar", ext)
}
}
}
func (e ePUBImagePassthrough) CoverTitleData(o epubimageprocessor.CoverTitleDataOptions) (epubzip.Image, error) {
return epubimageprocessor.New(e.EPUBOptions).CoverTitleData(o)
}
var errNoImagesFound = errors.New("no images found")
func New(o epuboptions.EPUBOptions) epubimageprocessor.EPUBImageProcessor {
return ePUBImagePassthrough{o}
}
func (e ePUBImagePassthrough) loadDir() (images []epubimage.EPUBImage, err error) {
imagesPath := make([]string, 0)
input := filepath.Clean(e.Input)
err = filepath.WalkDir(input, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && e.isSupportedImage(path) {
imagesPath = append(imagesPath, path)
}
return nil
})
if err != nil {
return
}
if len(imagesPath) == 0 {
err = errNoImagesFound
return
}
sort.Sort(sortpath.By(imagesPath, e.SortPathMode))
var imgStorage epubzip.StorageImageWriter
imgStorage, err = epubzip.NewStorageImageWriter(e.ImgStorage(), e.Image.Format)
if err != nil {
return
}
defer imgStorage.Close()
// processing
bar := epubprogress.New(epubprogress.Options{
Quiet: e.Quiet,
Json: e.Json,
Max: len(imagesPath),
Description: "Copying",
CurrentJob: 1,
TotalJob: 2,
})
defer bar.Close()
for i, imgPath := range imagesPath {
var img epubimage.EPUBImage
img, err = e.copyRawDataToStorage(
imgStorage,
func() ([]byte, error) {
f, err := os.Open(imgPath)
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
},
i,
input,
imgPath,
)
if err != nil {
return
}
images = append(images, img)
_ = bar.Add(1)
}
if len(images) == 0 {
err = errNoImagesFound
}
return
}
func (e ePUBImagePassthrough) loadCbz() (images []epubimage.EPUBImage, err error) {
images = make([]epubimage.EPUBImage, 0)
input := filepath.Clean(e.Input)
r, err := zip.OpenReader(input)
if err != nil {
return
}
defer r.Close()
imagesZip := make([]*zip.File, 0)
for _, f := range r.File {
if !f.FileInfo().IsDir() && e.isSupportedImage(f.Name) {
imagesZip = append(imagesZip, f)
}
}
if len(imagesZip) == 0 {
err = errNoImagesFound
return
}
var names []string
for _, img := range imagesZip {
names = append(names, img.Name)
}
sort.Sort(sortpath.By(names, e.SortPathMode))
indexedNames := make(map[string]int)
for i, name := range names {
indexedNames[name] = i
}
var imgStorage epubzip.StorageImageWriter
imgStorage, err = epubzip.NewStorageImageWriter(e.ImgStorage(), e.Image.Format)
if err != nil {
return
}
defer imgStorage.Close()
// processing
bar := epubprogress.New(epubprogress.Options{
Quiet: e.Quiet,
Json: e.Json,
Max: len(imagesZip),
Description: "Copying",
CurrentJob: 1,
TotalJob: 2,
})
defer bar.Close()
for _, imgZip := range imagesZip {
if _, ok := indexedNames[imgZip.Name]; !ok {
continue
}
var img epubimage.EPUBImage
img, err = e.copyRawDataToStorage(
imgStorage,
func() ([]byte, error) {
f, err := imgZip.Open()
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
},
indexedNames[imgZip.Name],
"",
imgZip.Name,
)
if err != nil {
return
}
images = append(images, img)
_ = bar.Add(1)
}
if len(images) == 0 {
err = errNoImagesFound
}
return
}
func (e ePUBImagePassthrough) loadCbr() (images []epubimage.EPUBImage, err error) {
images = make([]epubimage.EPUBImage, 0)
var isSolid bool
files, err := rardecode.List(e.Input)
if err != nil {
return
}
names := make([]string, 0)
for _, f := range files {
if !f.IsDir && e.isSupportedImage(f.Name) {
if f.Solid {
isSolid = true
}
names = append(names, f.Name)
}
}
if len(names) == 0 {
err = errNoImagesFound
return
}
sort.Sort(sortpath.By(names, e.SortPathMode))
indexedNames := make(map[string]int)
for i, name := range names {
indexedNames[name] = i
}
var imgStorage epubzip.StorageImageWriter
imgStorage, err = epubzip.NewStorageImageWriter(e.ImgStorage(), e.Image.Format)
if err != nil {
return
}
defer imgStorage.Close()
// processing
bar := epubprogress.New(epubprogress.Options{
Quiet: e.Quiet,
Json: e.Json,
Max: len(names),
Description: "Copying",
CurrentJob: 1,
TotalJob: 2,
})
defer bar.Close()
if isSolid {
var r *rardecode.ReadCloser
r, err = rardecode.OpenReader(e.Input)
if err != nil {
return
}
defer r.Close()
for {
f, rerr := r.Next()
if rerr != nil {
if rerr == io.EOF {
break
}
err = rerr
return
}
if _, ok := indexedNames[f.Name]; !ok {
continue
}
var img epubimage.EPUBImage
img, err = e.copyRawDataToStorage(
imgStorage,
func() ([]byte, error) {
return io.ReadAll(r)
},
indexedNames[f.Name],
"",
f.Name,
)
if err != nil {
return
}
images = append(images, img)
_ = bar.Add(1)
}
} else {
for _, file := range files {
if i, ok := indexedNames[file.Name]; ok {
var img epubimage.EPUBImage
img, err = e.copyRawDataToStorage(
imgStorage,
func() ([]byte, error) {
f, err := file.Open()
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
},
i,
"",
file.Name,
)
if err != nil {
return
}
images = append(images, img)
_ = bar.Add(1)
}
}
}
if len(images) == 0 {
err = errNoImagesFound
}
return
}
func (e ePUBImagePassthrough) isSupportedImage(path string) bool {
switch strings.ToLower(filepath.Ext(path)) {
case ".jpg", ".jpeg", ".png":
{
return !strings.HasPrefix(filepath.Base(path), ".")
}
}
return false
}
func (e ePUBImagePassthrough) copyRawDataToStorage(
imgStorage epubzip.StorageImageWriter,
getData func() ([]byte, error),
id int,
dirname string,
filename string,
) (img epubimage.EPUBImage, err error) {
var uncompressedData []byte
uncompressedData, err = getData()
if err != nil {
return
}
p, fn := filepath.Split(filepath.Clean(filename))
if p == dirname {
p = ""
} else {
p = p[len(dirname)+1:]
}
var (
format string
decodeConfig func(r io.Reader) (image.Config, error)
decode func(r io.Reader) (image.Image, error)
)
switch filepath.Ext(fn) {
case ".png":
format = "png"
decodeConfig = png.DecodeConfig
decode = png.Decode
case ".jpg", ".jpeg":
format = "jpeg"
decodeConfig = jpeg.DecodeConfig
decode = jpeg.Decode
}
var config image.Config
config, err = decodeConfig(bytes.NewReader(uncompressedData))
if err != nil {
return
}
var rawImage image.Image
if id == 0 {
rawImage, err = decode(bytes.NewReader(uncompressedData))
if err != nil {
return
}
}
img = epubimage.EPUBImage{
Id: id,
Part: 0,
Raw: rawImage,
Width: config.Width,
Height: config.Height,
IsBlank: false,
DoublePage: config.Width > config.Height,
Path: p,
Name: fn,
Format: format,
OriginalAspectRatio: float64(config.Height) / float64(config.Width),
}
err = imgStorage.AddRaw(img.EPUBImgPath(), uncompressedData)
return
}

View File

@ -43,7 +43,7 @@ type task struct {
var errNoImagesFound = errors.New("no images found")
// only accept jpg, png and webp as source file
func (e EPUBImageProcessor) isSupportedImage(path string) bool {
func (e ePUBImageProcessor) isSupportedImage(path string) bool {
switch strings.ToLower(filepath.Ext(path)) {
case ".jpg", ".jpeg", ".png", ".webp", ".tiff":
{
@ -53,8 +53,8 @@ func (e EPUBImageProcessor) isSupportedImage(path string) bool {
return false
}
// Load images from input
func (e EPUBImageProcessor) load() (totalImages int, output chan task, err error) {
// load images from input
func (e ePUBImageProcessor) load() (totalImages int, output chan task, err error) {
fi, err := os.Stat(e.Input)
if err != nil {
return
@ -78,7 +78,7 @@ func (e EPUBImageProcessor) load() (totalImages int, output chan task, err error
}
}
func (e EPUBImageProcessor) corruptedImage(path, name string) image.Image {
func (e ePUBImageProcessor) corruptedImage(path, name string) image.Image {
var w, h float64 = 1200, 1920
f, _ := truetype.Parse(gomonobold.TTF)
face := truetype.NewFace(f, &truetype.Options{Size: 64, DPI: 72})
@ -102,7 +102,7 @@ func (e EPUBImageProcessor) corruptedImage(path, name string) image.Image {
}
// load a directory of images
func (e EPUBImageProcessor) loadDir() (totalImages int, output chan task, err error) {
func (e ePUBImageProcessor) loadDir() (totalImages int, output chan task, err error) {
images := make([]string, 0)
input := filepath.Clean(e.Input)
@ -191,7 +191,7 @@ func (e EPUBImageProcessor) loadDir() (totalImages int, output chan task, err er
}
// load a zip file that include images
func (e EPUBImageProcessor) loadCbz() (totalImages int, output chan task, err error) {
func (e ePUBImageProcessor) loadCbz() (totalImages int, output chan task, err error) {
r, err := zip.OpenReader(e.Input)
if err != nil {
return
@ -277,7 +277,7 @@ func (e EPUBImageProcessor) loadCbz() (totalImages int, output chan task, err er
}
// load a rar file that include images
func (e EPUBImageProcessor) loadCbr() (totalImages int, output chan task, err error) {
func (e ePUBImageProcessor) loadCbr() (totalImages int, output chan task, err error) {
var isSolid bool
files, err := rardecode.List(e.Input)
if err != nil {
@ -393,7 +393,7 @@ func (e EPUBImageProcessor) loadCbr() (totalImages int, output chan task, err er
}
// extract image from a pdf
func (e EPUBImageProcessor) loadPdf() (totalImages int, output chan task, err error) {
func (e ePUBImageProcessor) loadPdf() (totalImages int, output chan task, err error) {
pdf := pdfread.Load(e.Input)
if pdf == nil {
err = fmt.Errorf("can't read pdf")

View File

@ -17,16 +17,21 @@ import (
"github.com/celogeek/go-comic-converter/v3/pkg/epuboptions"
)
type EPUBImageProcessor struct {
type EPUBImageProcessor interface {
Load() (images []epubimage.EPUBImage, err error)
CoverTitleData(o CoverTitleDataOptions) (epubzip.Image, error)
}
type ePUBImageProcessor struct {
epuboptions.EPUBOptions
}
func New(o epuboptions.EPUBOptions) EPUBImageProcessor {
return EPUBImageProcessor{o}
return ePUBImageProcessor{o}
}
// Load extract and convert images
func (e EPUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
func (e ePUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
images = make([]epubimage.EPUBImage, 0)
imageCount, imageInput, err := e.load()
if err != nil {
@ -136,7 +141,7 @@ func (e EPUBImageProcessor) Load() (images []epubimage.EPUBImage, err error) {
return images, nil
}
func (e EPUBImageProcessor) createImage(src image.Image, r image.Rectangle) draw.Image {
func (e ePUBImageProcessor) createImage(src image.Image, r image.Rectangle) draw.Image {
if e.EPUBOptions.Image.GrayScale {
return image.NewGray(r)
}
@ -169,7 +174,7 @@ func (e EPUBImageProcessor) createImage(src image.Image, r image.Rectangle) draw
// transform image into 1 or 3 images
// only doublepage with autosplit has 3 versions
func (e EPUBImageProcessor) transformImage(input task, part int, right bool) epubimage.EPUBImage {
func (e ePUBImageProcessor) transformImage(input task, part int, right bool) epubimage.EPUBImage {
g := gift.New()
src := input.Image
srcBounds := src.Bounds()
@ -286,7 +291,7 @@ type CoverTitleDataOptions struct {
BorderSize int
}
func (e EPUBImageProcessor) Cover16LevelOfGray(bounds image.Rectangle) draw.Image {
func (e ePUBImageProcessor) cover16LevelOfGray(bounds image.Rectangle) draw.Image {
return image.NewPaletted(bounds, color.Palette{
color.Gray{},
color.Gray{Y: 0x11},
@ -308,20 +313,20 @@ func (e EPUBImageProcessor) Cover16LevelOfGray(bounds image.Rectangle) draw.Imag
}
// CoverTitleData create a title page with the cover
func (e EPUBImageProcessor) CoverTitleData(o CoverTitleDataOptions) (epubzip.Image, error) {
func (e ePUBImageProcessor) CoverTitleData(o CoverTitleDataOptions) (epubzip.Image, error) {
// Create a blur version of the cover
g := gift.New(epubimagefilters.CoverTitle(o.Text, o.Align, o.PctWidth, o.PctMargin, o.MaxFontSize, o.BorderSize))
var dst draw.Image
if o.Name == "cover" && e.Image.GrayScale {
dst = e.Cover16LevelOfGray(o.Src.Bounds())
dst = e.cover16LevelOfGray(o.Src.Bounds())
} else {
dst = e.createImage(o.Src, g.Bounds(o.Src.Bounds()))
}
g.Draw(dst, o.Src)
return epubzip.CompressImage(
"OEBPS/Images/"+o.Name+"."+e.Image.Format,
e.Image.Format,
"OEBPS/Images/"+o.Name+".jpeg",
"jpeg",
dst,
e.Image.Quality,
)

View File

@ -144,7 +144,7 @@ func (o Content) getManifest() []tag {
var imageTags, pageTags, spaceTags []tag
addTag := func(img epubimage.EPUBImage, withSpace bool) {
imageTags = append(imageTags,
tag{"item", tagAttrs{"id": img.ImgKey(), "href": img.ImgPath(), "media-type": o.ImageOptions.MediaType()}, ""},
tag{"item", tagAttrs{"id": img.ImgKey(), "href": img.ImgPath(), "media-type": img.MediaType()}, ""},
)
pageTags = append(pageTags,
tag{"item", tagAttrs{"id": img.PageKey(), "href": img.PagePath(), "media-type": "application/xhtml+xml"}, ""},
@ -160,13 +160,13 @@ func (o Content) getManifest() []tag {
{"item", tagAttrs{"id": "toc", "href": "toc.xhtml", "properties": "nav", "media-type": "application/xhtml+xml"}, ""},
{"item", tagAttrs{"id": "css", "href": "Text/style.css", "media-type": "text/css"}, ""},
{"item", tagAttrs{"id": "page_cover", "href": "Text/cover.xhtml", "media-type": "application/xhtml+xml"}, ""},
{"item", tagAttrs{"id": "img_cover", "href": "Images/cover." + o.ImageOptions.Format, "media-type": o.ImageOptions.MediaType()}, ""},
{"item", tagAttrs{"id": "img_cover", "href": "Images/cover.jpeg", "media-type": "image/jpeg"}, ""},
}
if o.HasTitlePage {
items = append(items,
tag{"item", tagAttrs{"id": "page_title", "href": "Text/title.xhtml", "media-type": "application/xhtml+xml"}, ""},
tag{"item", tagAttrs{"id": "img_title", "href": "Images/title." + o.ImageOptions.Format, "media-type": o.ImageOptions.MediaType()}, ""},
tag{"item", tagAttrs{"id": "img_title", "href": "Images/title.jpeg", "media-type": "image/jpeg"}, ""},
)
if !o.ImageOptions.View.PortraitOnly {

View File

@ -66,3 +66,39 @@ func CompressImage(filename string, format string, img image.Image, quality int)
cdata.Bytes(),
}, nil
}
func CompressRaw(filename string, uncompressedData []byte) (Image, error) {
var (
cdata bytes.Buffer
err error
)
wcdata, err := flate.NewWriter(&cdata, flate.BestCompression)
if err != nil {
return Image{}, err
}
_, err = wcdata.Write(uncompressedData)
if err != nil {
return Image{}, err
}
err = wcdata.Close()
if err != nil {
return Image{}, err
}
t := time.Now()
//goland:noinspection GoDeprecation
return Image{
&zip.FileHeader{
Name: filename,
CompressedSize64: uint64(cdata.Len()),
UncompressedSize64: uint64(len(uncompressedData)),
CRC32: crc32.Checksum(uncompressedData, crc32.IEEETable),
Method: zip.Deflate,
ModifiedTime: uint16(t.Second()/2 + t.Minute()<<5 + t.Hour()<<11),
ModifiedDate: uint16(t.Day() + int(t.Month())<<5 + (t.Year()-1980)<<9),
},
cdata.Bytes(),
}, nil
}

View File

@ -50,3 +50,24 @@ func (e StorageImageWriter) Add(filename string, img image.Image, quality int) e
return nil
}
func (e StorageImageWriter) AddRaw(filename string, uncompressedData []byte) error {
zipImage, err := CompressRaw(filename, uncompressedData)
if err != nil {
return err
}
e.mut.Lock()
defer e.mut.Unlock()
fh, err := e.fz.CreateRaw(zipImage.Header)
if err != nil {
return err
}
_, err = fh.Write(zipImage.Data)
if err != nil {
return err
}
return nil
}

View File

@ -15,6 +15,7 @@ import (
"github.com/gofrs/uuid"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimage"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimagepassthrough"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubimageprocessor"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubprogress"
"github.com/celogeek/go-comic-converter/v3/internal/pkg/epubtemplates"
@ -52,13 +53,20 @@ func New(options epuboptions.EPUBOptions) EPUB {
"zoom": func(s int, z float32) int { return int(float32(s) * z) },
})
var imageProcessor epubimageprocessor.EPUBImageProcessor
if options.Image.Format == "copy" {
imageProcessor = epubimagepassthrough.New(options)
} else {
imageProcessor = epubimageprocessor.New(options)
}
return epub{
EPUBOptions: options,
UID: uid.String(),
Publisher: "GO Comic Converter",
UpdatedAt: time.Now().UTC().Format("2006-01-02T15:04:05Z"),
templateProcessor: tmpl,
imageProcessor: epubimageprocessor.New(options),
imageProcessor: imageProcessor,
}
}
@ -115,7 +123,7 @@ func (e epub) writeCoverImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, part,
[]byte(e.render(epubtemplates.Text, map[string]any{
"Title": title,
"ViewPort": e.Image.View.Port(),
"ImagePath": "Images/cover." + e.Image.Format,
"ImagePath": "Images/cover.jpeg",
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, ""),
})),
); err != nil {
@ -172,7 +180,7 @@ func (e epub) writeTitleImage(wz epubzip.EPUBZip, img epubimage.EPUBImage, title
[]byte(e.render(epubtemplates.Text, map[string]any{
"Title": title,
"ViewPort": e.Image.View.Port(),
"ImagePath": "Images/title." + e.Image.Format,
"ImagePath": "Images/title.jpeg",
"ImageStyle": img.ImgStyle(e.Image.View.Width, e.Image.View.Height, titleAlign),
})),
); err != nil {

View File

@ -20,7 +20,3 @@ type Image struct {
Format string `yaml:"format" json:"format"`
AppleBookCompatibility bool `yaml:"apple_book_compatibility" json:"apple_book_compatibility"`
}
func (i Image) MediaType() string {
return "image/" + i.Format
}