Search code examples
gogo-gin

How to change the resolution of an image?


How do I change the resolution of this image before uploading?

f, uploadedFile, err := c.Request.FormFile("file") // image file
if err != nil {
    c.JSON(http.StatusInternalServerError, gin.H{
        "message": err.Error(),
        "error":   true,
    })
    return
}

fullcode: paste.ofcode.org/4wvAGNxZDmpqZ2Zucujmnw


Solution

  • As said icza you'll need an external lib to do that,
    there is the basic : resize which is no longer maintained
    and the bigger : imaging

    In both case you'll need to get the standard image struct before using a resize lib.

    that would look like something like this :

    import(
    "image"
    github.com/disintegration/imaging
    [...]
    )
    [...]
    
    f, uploadedFile, err := c.Request.FormFile("file") // image file
    
    // Decode the file into a image struct
    var srcImg image.Image
    srcImg, _, err = image.Decode(f)
    
    // Resize srcImage to width = 800px preserving the aspect ratio.
    dstImage800 := imaging.Resize(srcImg, 800, 0, imaging.Lanczos)