disintegration / imaging

Imaging is a simple image processing package for Go
MIT License
5.3k stars 443 forks source link

Huge image size after resize it #126

Closed max107 closed 4 years ago

max107 commented 4 years ago

Can you describe please, why image files very huge?

package main

import (
    "github.com/disintegration/imaging"
)

func main() {
    // initial image size 688x768 ~120K
    img, _ := imaging.Open("a1e7f78b268953dd2ddec8389ceddc49.jpg")

    // first thumbnail 615x615 ~256K
    th1 := imaging.Thumbnail(img, 615, 615, imaging.Lanczos)
    _ = imaging.Save(th1, "1.jpg", imaging.JPEGQuality(95))

    // second thumbnail 1280x960 ~448K
    th2 := imaging.Thumbnail(img, 1280, 960, imaging.Lanczos)
    _ = imaging.Save(th2, "2.jpg", imaging.JPEGQuality(95))
}

Imagick: convert -define jpeg:size=688x768 a1e7f78b268953dd2ddec8389ceddc49.jpg -thumbnail '615x615>' 1.jpg = ~128K

a1e7f78b268953dd2ddec8389ceddc49

disintegration commented 4 years ago

You can use smaller JPEGQuality values to get smaller JPEG file sizes.

max107 commented 4 years ago

Okay, i can. But how about my question? If i resized image from 100kb with 300x300 to same size 300x300 i receive 300kb file. It's normal behavior? Why image size increased to 2-3 times?

disintegration commented 4 years ago

Yes, it's a normal behavior. If the image was originally saved using lower quality settings, then after loading and re-saving with higher quality the file size will icrease.

max107 commented 4 years ago

hmmm....

dont change image, just resave

package main

import (
    "github.com/disintegration/imaging"
    "github.com/h2non/bimg"
)

func main() {
    img, _ := imaging.Open("src.jpg")
    _ = imaging.Save(img, "2.jpg")

    buff, _ := bimg.Read("src.jpg")
    bimg.Write("1.jpg", bimg.NewImage(buff).Image())
}
du -sx src.jpg 1.jpg 2.jpg
240 src.jpg
240 1.jpg
456 2.jpg

resize image and save

package main

import (
    "github.com/disintegration/imaging"
    "github.com/h2non/bimg"
)

func main() {
    img, _ := imaging.Open("src.jpg")
    th1 := imaging.Resize(img, 688, 768, imaging.Box)
    _ = imaging.Save(th1, "2.jpg")

    buff, _ := bimg.Read("src.jpg")
    thumb := bimg.NewImage(buff)
    _, _ = thumb.Resize(688, 768)
    bimg.Write("1.jpg", thumb.Image())
}
du -sx src.jpg 1.jpg 2.jpg
240 src.jpg
256 1.jpg
512 2.jpg
vorlif commented 4 years ago

Yes, imaging has a default quality value of 95 while bimg has a default value of 80. So you have to use a smaller value for quality as @disintegration wrote.

Try the example from the documentation

// Save the image as JPEG with optional quality parameter set to 80.
err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))
disintegration commented 4 years ago

The imaging package itself does not implement JPEG encoding. It uses the standard "image/jpeg" package. The only way to reduce an image size is to use the quality parameter (imaging.JPEGQuality option).