如何转换图像以上传 Spotify 个人资料图片?

How do I convert an image to upload a Spotify profile picture?

我正在设置图像编码器功能,您可以在其中输入图像 URL 并且它 returns 是它的 ISO-8859-1 版本。我将如何编写一个向 URL 发送 HTTP GET 请求并将这些字节转换为 ISO-8859-1 的函数?下面的代码是我目前所有的代码。

func grabImageBytes(imageURL string) ([]byte, error) {
    req, _ := http.NewRequest("GET", imageURL, nil)
    res, _ := http.DefaultClient.Do(req)
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        return nil, err
    } else {
        return body, nil
    }
}

其他功能:

func getRandomImage(keyword string) (string, error) {
    req, _ := http.NewRequest("GET", "https://www.google.com/search?tbm=isch&q="+keyword, nil)
    req.Header.Add("authority", "www.google.com")
    req.Header.Add("upgrade-insecure-requests", "1")
    req.Header.Add("referer", "https://images.google.com/")
    req.Header.Add("accept-language", "en-US,en;q=0.9")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    var imageURL string

    if strings.Contains(string(body), ",\"ou\":\"") {
        imageURL = strings.Split(strings.Split(string(body), ",\"ou\":\"")[1], "\",\"ow\":")[0]
    } else {
        return "", errors.New("Image not found.")
    }
    req2, _ := http.NewRequest("GET", imageURL, nil)

    res2, _ := http.DefaultClient.Do(req2)

    defer res2.Body.Close()
    if res2.StatusCode == 404 {
        return "", errors.New("Image not found.")
    } else {
        return imageURL, nil
    }

}

您声称 Spotify 个人资料图片是 ISO 8850-1 encoded/encrypted 毫无意义。

更有意义的是它是 Base64 编码的。

例如,

Spotify for Developers: Web API: Upload a Custom Playlist Cover Image.

Base64 encoded JPEG image data, maximum payload size is 256 KB


在围棋中,

Package base64

import "encoding/base64"

Package base64 implements base64 encoding as specified by RFC 4648.


另一个证据:"HTTPS requests in UTF-8 format"

Spotify for Developers: Web API

Requests

The Spotify Web API is based on REST principles. Data resources are accessed via standard HTTPS requests in UTF-8 format to an API endpoint.


例如。使用您的 Stack Overflow 个人资料图片:

package main

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

func grabImageBytes(imageURL string) ([]byte, error) {
    req, err := http.NewRequest("GET", imageURL, nil)
    if err != nil {
        return nil, err
    }
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        return nil, err
    }
    enc := base64.StdEncoding
    img := make([]byte, enc.EncodedLen(len(body)))
    enc.Encode(img, body)
    return img, nil
}

func main() {
    imageURL := `https://lh5.googleusercontent.com/-P8ICR-LXoBs/AAAAAAAAAAI/AAAAAAAAE04/fVAeB6_nMeg/photo.jpg?sz=328`
    img, err := grabImageBytes(imageURL)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    fmt.Println(string(img))
}