nfnt / resize

Pure golang image resizing
ISC License
3.02k stars 321 forks source link

Increased file size after resizing (downscaling) #54

Closed danhardman closed 7 years ago

danhardman commented 7 years ago

I've noticed that when images are resized, specifically when they're reduced in size, the resulting file size is larger than the original. I'm not sure if I'm misunderstanding something but I'd expect the file size to decrease with the size of the image.

width := 10
height := 10

img, format, err := image.Decode(bytes.NewReader(file))
if err != nil {
    return nil, "", err
}
//Only resize if new dimensions are specified
if width != 0 || height != 0 {
    img = resize.Resize(width, height, img, resize.Lanczos3)
}
var buf bytes.Buffer
switch format {
case "jpeg":
    jpeg.Encode(&buf, img, nil)
case "png":
    png.Encode(&buf, img)
case "gif":
    gif.Encode(&buf, img, nil)
default:
    return nil, "", errors.New("not an image")
}

data := buf.Bytes()
fmt.Printf("Size: %d", binary.Size(data))

In this case, I'm serving the images from a web server and I've implemented this resizing to decrease request sizes. In one example, the original request with no resizing is 755B. With resizing the image to half its size, the request size is 4.5KB.

Any suggestions?

matrixik commented 7 years ago

Is source image heavily striped and compressed with some lossless compressors?

Some info here: https://www.raymond.cc/blog/4-free-tools-to-optimize-and-compress-png-images-without-loosing-quality/ Some nice tool that integrate some of them in one tool: http://css-ig.net/pingo

danhardman commented 7 years ago

The image was: http://i.imgur.com/3Tem67v.png The images will be user provided so I can't play around with optimising the image. I've tried https://github.com/disintegration/imaging which seems to have better results.

Thanks!

nfnt commented 7 years ago

Yeah, could be possible. PNG does lossless compression but some parameters can be tuned to get an even better compression. Also metadata could be removed etc. png.Encode probably does nothing like that (just guessing), so the result may be bigger. Especially true if the input image is small to begin with (755 bytes is very small). Try running something pngcrush on the output image, the filesize should be smaller afterwards. Anyways, this is not related to this package but to image file handling, so I'm closing this ticket here.

danhardman commented 7 years ago

I disagree that this issue isn't to do with this package. The increase in file size happens only when the image is resized. I made sure encoding was the same on each test to make sure :)

My problem is solved though so no worries! Thanks