Golang将URL中的图片转换为Base64编码字符串

Golang将URL中的图片转换为Base64编码字符串 请帮助将位于AWS存储桶URL路径上的图像转换为base64编码字符串。

2 回复

尝试这个: b64 “encoding/base64” -> https://golang.org/pkg/encoding/base64/

在这个示例中,我已经在减小图片尺寸

GitHub

nfnt/resize

resize - 纯 Golang 图片缩放

头像

file, _, err := req.FormFile("image")
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			defer file.Close()
			img, _, err := image.Decode(file)
			m := resize.Resize(135, 115, img, resize.Lanczos3)
			buf := new(bytes.Buffer)
			err = jpeg.Encode(buf, m, &jpeg.Options{35})
			imageBit := buf.Bytes()
			/*Defining the new image size*/

			photoBase64 := b64.StdEncoding.EncodeToString([]byte(imageBit))
			fmt.Println("Photo Base64.............................:" + fotoBase64)

更多关于Golang将URL中的图片转换为Base64编码字符串的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,可以通过以下步骤将AWS存储桶URL中的图片转换为Base64编码字符串。首先,使用HTTP GET请求获取图像数据,然后将其编码为Base64格式。以下是完整的代码示例:

package main

import (
    "encoding/base64"
    "fmt"
    "io"
    "net/http"
)

func main() {
    // 假设AWS存储桶的图片URL
    imageURL := "https://your-bucket.s3.amazonaws.com/path/to/image.jpg"

    // 发送HTTP GET请求获取图像
    resp, err := http.Get(imageURL)
    if err != nil {
        fmt.Printf("获取图像失败: %v\n", err)
        return
    }
    defer resp.Body.Close()

    // 检查HTTP响应状态
    if resp.StatusCode != http.StatusOK {
        fmt.Printf("HTTP请求失败,状态码: %d\n", resp.StatusCode)
        return
    }

    // 读取图像数据
    imageData, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("读取图像数据失败: %v\n", err)
        return
    }

    // 将图像数据转换为Base64编码字符串
    base64String := base64.StdEncoding.EncodeToString(imageData)

    // 输出Base64字符串(在实际应用中,可能需要处理或存储它)
    fmt.Println("Base64编码字符串:")
    fmt.Println(base64String)
}

代码说明:

  1. 导入包:使用net/http进行HTTP请求,io读取响应体,encoding/base64进行Base64编码。
  2. HTTP GET请求:通过http.Get获取图像数据,并检查响应状态码是否为200 OK。
  3. 读取数据:使用io.ReadAll将响应体读取为字节切片。
  4. Base64编码:使用base64.StdEncoding.EncodeToString将字节数据转换为Base64字符串。

注意事项:

  • 确保URL可公开访问或已配置适当的AWS凭证(如果存储桶是私有的,需在请求中添加认证头)。
  • 对于大图像,考虑使用流式处理以避免内存问题,但此示例适用于常见大小的图像。

运行此代码将输出图像的Base64编码字符串,可直接用于嵌入HTML或存储。

回到顶部