#png or jpg compression

21 messages · Page 1 of 1 (latest)

livid dust
#

Hey there i'd like to upload some picture on twitter but due to a size limitation i can't so i'd like to compress them a bit. i found this library : https://github.com/h2non/bimg but didn't found any example on how to convert a png to jpg, or just to compress an existing jpg file can someone help me please, this could be using the same library or another one

here is what i got but didn't managed to run it on windows to test it

package main

import (
    "fmt"
    "os"

    "github.com/h2non/bimg"
)

func main() {
    //convert png file to jpg with a quality of 80
    buffer, err := bimg.Read("2371.png")
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    }

    newImage, err := bimg.NewImage(buffer).Convert(bimg.JPEG)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    }

    err = bimg.Write("image.jpg", newImage)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    }

}
GitHub

Go package for fast high-level image processing powered by libvips C library - GitHub - h2non/bimg: Go package for fast high-level image processing powered by libvips C library

coarse aurora
#

You should be able to just post a PNG to Twitter?
How far over the size limit are you?

livid dust
#

3Mb max from what i saw on github

#

just found a way to do it using image library

coarse aurora
#

Also, reading as PNG and writing as JPEG can be done with the built in img/png and img/jpeg packages, not sure what h2non/bimg does.

livid dust
coarse aurora
#

Yes, but how big is the image you're trying to post? If it's 30MB then simply converting to JPEG won't help.

livid dust
#

oh nope it's like 4 or 5

#

but once i convert png to jpeg even with quality set to 100 seems okay

#
package main

import (
    "image"
    "image/jpeg"
    "log"
    "net/http"
    "os"

    _ "image/png"
)

func main() {

    // get image from url
    resp, err := http.Get("url")
    if err != nil {
        log.Fatal(err)
    }

    defer resp.Body.Close()

    // decode image
    img, _, err := image.Decode(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    // encode image
    f, err := os.Create("image.jpg")
    if err != nil {
        log.Fatal(err)
    }

    // use quality 80
    err = jpeg.Encode(f, img, &jpeg.Options{Quality: 100})
    if err != nil {
        log.Fatal(err)
    }

}

#

this seems to work for me

coarse aurora
#

But yeah, stdlib love for sure.

livid dust
#

not sure how twitter handles it may give it a try too

livid dust
coarse aurora
#

I think Twitter were involved in creating WebP 🤷

coarse aurora
#

Like image conversion. It just does the thing.

livid dust
#

oh yeah actually i'm pretty new to golang, i mainly do my things on python and always prefer using std libs instead of importing many other libs

coarse aurora