GetImageFromUrl 获取图片的类型和base64编码的数据
(url string)
| 61 | |
| 62 | // GetImageFromUrl 获取图片的类型和base64编码的数据 |
| 63 | func 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 | |
| 113 | func DecodeUrlImageData(imageUrl string) (image.Config, string, error) { |
| 114 | response, err := DoDownloadRequest(imageUrl) |
no test coverage detected