[Golang] Resize Image

·

1 min read

Resize image

Screen Shot 2022-11-16 at 08.33.03.png

Code Example:

  • function input image-base64 and output is a image:
func ResizeImageFromBase64(imgBase64 string, newHeight int) (string, error) {
    // convert image is base64 to byte
    unbased, err := base64.StdEncoding.DecodeString(imgBase64)
    if err != nil {
        return "", fmt.Errorf("cannot decode base64 err=%v", err)
    }

    r := bytes.NewReader(unbased)
    // use library imaging
    // parse reader to image
    img, err := imaging.Decode(r)
    if err != nil {
        return "", err
    }

    // calculator new width of image
    newWidth := newHeight * img.Bounds().Max.X / img.Bounds().Max.Y

    // resize new image
    nrgba := imaging.Resize(img, newWidth, newHeight, imaging.Lanczos)

    return toBase64(nrgba)
}
  • function toBase64 convert image to base
func toBase64(dst *image.NRGBA) (string, error) {
    var b bytes.Buffer
    foo := bufio.NewWriter(&b)
    if err := imaging.Encode(foo, dst, imaging.JPEG); err != nil {
        return "", err
    }
    return base64.StdEncoding.EncodeToString(b.Bytes()), nil
}

IF you extremely helpful, please for me a star at here