How I Used ChatGPT to Write a Golang Image Compression Function
Recently, while developing the ImgURL client using Wails, I needed to compress images before uploading them. To improve efficiency and save time, I decided to let ChatGPT handle this task.

Stating the Requirements
I provided ChatGPT with the following requirements:
Please help me write a Golang function that accepts an image path and compresses it. The function should support JPG and PNG image formats and validate the MIME type. If the image type is not JPG or PNG, the function should not process it. The compressed image path should remain the same as the original path, for example,
/tmp/1.pngshould remain/tmp/1.pngafter compression. The function should return an error.
The first code returned did not validate the MIME type, so I asked for a follow-up:
It seems you are judging based on the file extension rather than the MIME type? Please judge based on the MIME type. If it does not match, return nil, and the compressed image path should not change, for example,
/tmp/1.pngshould remain/tmp/1.pngafter compression.
The code provided this time looked correct, but when actually run, the image was not compressed. It turned out the MIME type detection was incorrect, so I continued to ask:
Why is there no change in the image size after I call the function?
ChatGPT admitted its mistake:
Sorry for the trouble. I found an error in the code: the
http.DetectContentTypemethod should receive the first 512 bytes of the file rather than the file path. Below is the modifiedcompressImagefunction.
The code provided this time ran successfully without further modifications and compressed the images correctly.
package main
import (
"errors"
"image"
"image/jpeg"
"image/png"
"mime"
"net/http"
"os"
)
func compressImage(imagePath string) error {
file, err := os.Open(imagePath)
if err != nil {
return err
}
defer file.Close()
// Read the first 512 bytes of the file
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil {
return err
}
file.Seek(0, 0)
// Check based on MIME type
contentType := http.DetectContentType(buffer)
var img image.Image
var format string
switch contentType {
case "image/jpeg":
img, err = jpeg.Decode(file)
format = "jpeg"
case "image/png":
img, err = png.Decode(file)
format = "png"
default:
return nil
}
if err != nil {
return err
}
// Close and reopen the file for compression
file.Close()
file, err = os.OpenFile(imagePath, os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()
var opt jpeg.Options
opt.Quality = 75 // Set compression quality to 75
switch format {
case "jpeg":
err = jpeg.Encode(file, img, &opt)
case "png":
encoder := png.Encoder{CompressionLevel: png.BestCompression}
err = encoder.Encode(file, img)
}
return err
}
func main() {
imagePath := "/tmp/1.png"
err := compressImage(imagePath)
if err != nil {
println("Error compressing image:", err.Error())
} else {
println("Image compressed successfully")
}
}
The AI also provided an explanation for the code:
In this function, JPEG images use lossy compression, while PNG images use lossless compression.
For JPEG images, the compression quality is set to 75 (the range is 1-100; higher values mean better quality but larger file sizes).
For PNG images, the function uses the best compression level (png.BestCompression). This performs lossless compression, preserving all original image information, but may result in longer compression times.
Conclusion
Using ChatGPT correctly can indeed improve efficiency, but it cannot be fully relied upon. Critical thinking is still necessary because ChatGPT's answers are not always correct. We need to identify and guide the AI to get the right answers. Viewing ChatGPT as an auxiliary tool is very effective. Additionally, we should distinguish which questions can be answered by ChatGPT and which require our own solutions.
Friends who cannot directly use ChatGPT can also try AsBot: https://dwz.ovh/ab3iv