|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/md5" |
| 5 | + "encoding/hex" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "image" |
| 9 | + "image/jpeg" |
| 10 | + "image/png" |
| 11 | + "io" |
| 12 | + "net/http" |
| 13 | + "os" |
| 14 | + "path/filepath" |
| 15 | + "strings" |
| 16 | + |
| 17 | + "github.com/chai2010/webp" |
| 18 | + "github.com/gorilla/mux" |
| 19 | + "github.com/nfnt/resize" |
| 20 | +) |
| 21 | + |
| 22 | +var outputDirectory string |
| 23 | + |
| 24 | +func init() { |
| 25 | + flag.StringVar(&outputDirectory, "o", ".", "Output directory for compressed images") |
| 26 | + flag.Parse() |
| 27 | +} |
| 28 | + |
| 29 | +func downloadImage(url string) (image.Image, string, error) { |
| 30 | + resp, err := http.Get(url) |
| 31 | + if err != nil { |
| 32 | + return nil, "", err |
| 33 | + } |
| 34 | + defer resp.Body.Close() |
| 35 | + |
| 36 | + var img image.Image |
| 37 | + var format string |
| 38 | + |
| 39 | + // Determine the image format based on content type |
| 40 | + contentType := resp.Header.Get("Content-Type") |
| 41 | + switch { |
| 42 | + case strings.Contains(contentType, "jpeg"): |
| 43 | + img, _, err = image.Decode(resp.Body) |
| 44 | + format = "jpeg" |
| 45 | + case strings.Contains(contentType, "png"): |
| 46 | + img, _, err = image.Decode(resp.Body) |
| 47 | + format = "png" |
| 48 | + case strings.Contains(contentType, "webp"): |
| 49 | + img, err = webp.Decode(resp.Body) |
| 50 | + format = "webp" |
| 51 | + default: |
| 52 | + return nil, "", fmt.Errorf("unsupported image format") |
| 53 | + } |
| 54 | + |
| 55 | + if err != nil { |
| 56 | + return nil, "", err |
| 57 | + } |
| 58 | + |
| 59 | + return img, format, nil |
| 60 | +} |
| 61 | + |
| 62 | +func compressImage(img image.Image, format, output string, quality int, resolution string) error { |
| 63 | + // Resize the image if resolution is provided |
| 64 | + if resolution != "" { |
| 65 | + size := strings.Split(resolution, "x") |
| 66 | + width, height := parseResolution(size[0], size[1], img.Bounds().Dx(), img.Bounds().Dy()) |
| 67 | + img = resize.Resize(width, height, img, resize.Lanczos3) |
| 68 | + } |
| 69 | + |
| 70 | + // Create the output file in the specified directory |
| 71 | + out, err := os.Create(filepath.Join(outputDirectory, output)) |
| 72 | + if err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + defer out.Close() |
| 76 | + |
| 77 | + // Compress and save the image in the specified format |
| 78 | + switch format { |
| 79 | + case "jpeg": |
| 80 | + options := jpeg.Options{Quality: quality} |
| 81 | + err = jpeg.Encode(out, img, &options) |
| 82 | + case "png": |
| 83 | + encoder := png.Encoder{CompressionLevel: png.BestCompression} |
| 84 | + err = encoder.Encode(out, img) |
| 85 | + case "webp": |
| 86 | + options := &webp.Options{Lossless: true} |
| 87 | + err = webp.Encode(out, img, options) |
| 88 | + default: |
| 89 | + return fmt.Errorf("unsupported output format") |
| 90 | + } |
| 91 | + |
| 92 | + if err != nil { |
| 93 | + return err |
| 94 | + } |
| 95 | + |
| 96 | + return nil |
| 97 | +} |
| 98 | + |
| 99 | +func generateMD5Hash(input string) string { |
| 100 | + hasher := md5.New() |
| 101 | + hasher.Write([]byte(input)) |
| 102 | + return hex.EncodeToString(hasher.Sum(nil)) |
| 103 | +} |
| 104 | + |
| 105 | +func atoi(s string) int { |
| 106 | + result := 0 |
| 107 | + for _, c := range s { |
| 108 | + result = result*10 + int(c-'0') |
| 109 | + } |
| 110 | + return result |
| 111 | +} |
| 112 | + |
| 113 | +func parseResolution(width, height string, originalWidth, originalHeight int) (uint, uint) { |
| 114 | + var newWidth, newHeight uint |
| 115 | + |
| 116 | + if width == "auto" && height == "auto" { |
| 117 | + // If both dimensions are "auto," maintain the original size |
| 118 | + newWidth = uint(originalWidth) |
| 119 | + newHeight = uint(originalHeight) |
| 120 | + } else if width == "auto" { |
| 121 | + // If width is "auto," calculate height maintaining the aspect ratio |
| 122 | + ratio := float64(originalWidth) / float64(originalHeight) |
| 123 | + newHeight = uint(atoi(height)) |
| 124 | + newWidth = uint(float64(newHeight) * ratio) |
| 125 | + } else if height == "auto" { |
| 126 | + // If height is "auto," calculate width maintaining the aspect ratio |
| 127 | + ratio := float64(originalHeight) / float64(originalWidth) |
| 128 | + newWidth = uint(atoi(width)) |
| 129 | + newHeight = uint(float64(newWidth) * ratio) |
| 130 | + } else { |
| 131 | + // Use the provided width and height |
| 132 | + newWidth = uint(atoi(width)) |
| 133 | + newHeight = uint(atoi(height)) |
| 134 | + } |
| 135 | + |
| 136 | + return newWidth, newHeight |
| 137 | +} |
| 138 | + |
| 139 | +func compressHandler(w http.ResponseWriter, r *http.Request) { |
| 140 | + url := r.URL.Query().Get("url") |
| 141 | + format := r.URL.Query().Get("output") |
| 142 | + quality := r.URL.Query().Get("quality") |
| 143 | + resolution := r.URL.Query().Get("resolution") |
| 144 | + |
| 145 | + // Concatenate parameters into a single string |
| 146 | + paramsString := fmt.Sprintf("%s-%s-%s-%s", url, format, quality, resolution) |
| 147 | + |
| 148 | + // Generate MD5 hash from the concatenated parameters |
| 149 | + hash := generateMD5Hash(paramsString) |
| 150 | + |
| 151 | + // Generate the output filename using the hash and format |
| 152 | + output := fmt.Sprintf("%s.%s", hash, format) |
| 153 | + |
| 154 | + // Check if the compressed file already exists in the output directory |
| 155 | + filePath := filepath.Join(outputDirectory, output) |
| 156 | + if _, err := os.Stat(filePath); err == nil { |
| 157 | + // File exists, no need to download and compress again |
| 158 | + |
| 159 | + // Open and send the existing compressed image file |
| 160 | + compressedFile, err := os.Open(filePath) |
| 161 | + if err != nil { |
| 162 | + http.Error(w, fmt.Sprintf("Error opening compressed image file: %s", err), http.StatusInternalServerError) |
| 163 | + return |
| 164 | + } |
| 165 | + defer compressedFile.Close() |
| 166 | + |
| 167 | + // Set the appropriate Content-Type based on the output format |
| 168 | + var contentType string |
| 169 | + switch format { |
| 170 | + case "jpeg": |
| 171 | + contentType = "image/jpeg" |
| 172 | + case "png": |
| 173 | + contentType = "image/png" |
| 174 | + case "webp": |
| 175 | + contentType = "image/webp" |
| 176 | + default: |
| 177 | + http.Error(w, "Unsupported output format", http.StatusInternalServerError) |
| 178 | + return |
| 179 | + } |
| 180 | + |
| 181 | + // Set the Content-Type header |
| 182 | + w.Header().Set("Content-Type", contentType) |
| 183 | + |
| 184 | + // Copy the existing compressed image file to the response writer |
| 185 | + _, err = io.Copy(w, compressedFile) |
| 186 | + if err != nil { |
| 187 | + http.Error(w, fmt.Sprintf("Error sending compressed image: %s", err), http.StatusInternalServerError) |
| 188 | + return |
| 189 | + } |
| 190 | + |
| 191 | + return |
| 192 | + } |
| 193 | + |
| 194 | + img, imgFormat, err := downloadImage(url) |
| 195 | + if err != nil { |
| 196 | + http.Error(w, fmt.Sprintf("Error downloading image: %s", err), http.StatusInternalServerError) |
| 197 | + return |
| 198 | + } |
| 199 | + |
| 200 | + if format == "" { |
| 201 | + format = imgFormat |
| 202 | + } |
| 203 | + |
| 204 | + err = compressImage(img, format, output, atoi(quality), resolution) |
| 205 | + if err != nil { |
| 206 | + http.Error(w, fmt.Sprintf("Error compressing image: %s", err), http.StatusInternalServerError) |
| 207 | + return |
| 208 | + } |
| 209 | + |
| 210 | + // Set the appropriate Content-Type based on the output format |
| 211 | + var contentType string |
| 212 | + switch format { |
| 213 | + case "jpeg": |
| 214 | + contentType = "image/jpeg" |
| 215 | + case "png": |
| 216 | + contentType = "image/png" |
| 217 | + case "webp": |
| 218 | + contentType = "image/webp" |
| 219 | + default: |
| 220 | + http.Error(w, "Unsupported output format", http.StatusInternalServerError) |
| 221 | + return |
| 222 | + } |
| 223 | + |
| 224 | + // Set the Content-Type header |
| 225 | + w.Header().Set("Content-Type", contentType) |
| 226 | + |
| 227 | + // Open and send the compressed image file |
| 228 | + compressedFile, err := os.Open(filePath) |
| 229 | + if err != nil { |
| 230 | + http.Error(w, fmt.Sprintf("Error opening compressed image file: %s", err), http.StatusInternalServerError) |
| 231 | + return |
| 232 | + } |
| 233 | + defer compressedFile.Close() |
| 234 | + |
| 235 | + // Copy the compressed image file to the response writer |
| 236 | + _, err = io.Copy(w, compressedFile) |
| 237 | + if err != nil { |
| 238 | + http.Error(w, fmt.Sprintf("Error sending compressed image: %s", err), http.StatusInternalServerError) |
| 239 | + return |
| 240 | + } |
| 241 | + fmt.Fprintf(w, "Image compressed and saved to %s\n", filePath) |
| 242 | +} |
| 243 | + |
| 244 | + |
| 245 | + |
| 246 | +func main() { |
| 247 | + r := mux.NewRouter() |
| 248 | + r.HandleFunc("/compressor", compressHandler).Methods("GET") |
| 249 | + r.HandleFunc("/compressor/{filename}", compressHandler).Methods("GET") |
| 250 | + |
| 251 | + http.Handle("/", r) |
| 252 | + |
| 253 | + fmt.Printf("Server is listening on :8080. Output directory: %s\n", outputDirectory) |
| 254 | + http.ListenAndServe(":8080", nil) |
| 255 | +} |
0 commit comments