MCPcopy Create free account
hub / github.com/aiprodcoder/MIXAPI / GetImageFromUrl

Function GetImageFromUrl

service/image.go:63–111  ·  view source on GitHub ↗

GetImageFromUrl 获取图片的类型和base64编码的数据

(url string)

Source from the content-addressed store, hash-verified

61
62// GetImageFromUrl 获取图片的类型和base64编码的数据
63func GetImageFromUrl(url string) (mimeType string, data string, err error) {
64 resp, err := DoDownloadRequest(url)
65 if err != nil {
66 return "", "", fmt.Errorf("failed to download image: %w", err)
67 }
68 defer resp.Body.Close()
69
70 // Check HTTP status code
71 if resp.StatusCode != http.StatusOK {
72 return "", "", fmt.Errorf("failed to download image: HTTP %d", resp.StatusCode)
73 }
74
75 contentType := resp.Header.Get("Content-Type")
76 if contentType != "application/octet-stream" && !strings.HasPrefix(contentType, "image/") {
77 return "", "", fmt.Errorf("invalid content type: %s, required image/*", contentType)
78 }
79 maxImageSize := int64(constant.MaxFileDownloadMB * 1024 * 1024)
80
81 // Check Content-Length if available
82 if resp.ContentLength > maxImageSize {
83 return "", "", fmt.Errorf("image size %d exceeds maximum allowed size of %d bytes", resp.ContentLength, maxImageSize)
84 }
85
86 // Use LimitReader to prevent reading oversized images
87 limitReader := io.LimitReader(resp.Body, maxImageSize)
88 buffer := &bytes.Buffer{}
89
90 written, err := io.Copy(buffer, limitReader)
91 if err != nil {
92 return "", "", fmt.Errorf("failed to read image data: %w", err)
93 }
94 if written >= maxImageSize {
95 return "", "", fmt.Errorf("image size exceeds maximum allowed size of %d bytes", maxImageSize)
96 }
97
98 data = base64.StdEncoding.EncodeToString(buffer.Bytes())
99 mimeType = contentType
100
101 // Handle application/octet-stream type
102 if mimeType == "application/octet-stream" {
103 _, format, _, err := DecodeBase64ImageData(data)
104 if err != nil {
105 return "", "", err
106 }
107 mimeType = "image/" + format
108 }
109
110 return mimeType, data, nil
111}
112
113func DecodeUrlImageData(imageUrl string) (image.Config, string, error) {
114 response, err := DoDownloadRequest(imageUrl)

Callers 1

responseAli2OpenAIImageFunction · 0.92

Calls 4

DoDownloadRequestFunction · 0.85
DecodeBase64ImageDataFunction · 0.85
GetMethod · 0.80
CopyMethod · 0.80

Tested by

no test coverage detected