HomeToolsAbout a20k

Image Conversion

Convert, Resize, Quality

sourcePath := "original.png" const ( imageWidth = 160 // px jpegQuality = 50 // 50% ) // read the source path source_image_bytes, err := os.ReadFile(sourcePath) if err != nil { log.Printf("error opening local source image: %v", err) return } // content type detection on original asset contentType := http.DetectContentType(source_image_bytes) // convert image to jpeg when the content type is png if contentType == "image/png" { // Decode the PNG image bytes source_img_data, err := png.Decode(bytes.NewReader(source_image_bytes)) if err != nil { log.Printf("error decoding png image: %v", err) return } // convert to jpeg // initialize a new buffer to store the jpeg image conversion_buffer := new(bytes.Buffer) // export the decoded image to jpeg // Quality can be dropped or adjusted here jpeg.Encode(conversion_buffer, source_img_data, &jpeg.Options{Quality: 95}) // decode to convert buffer to image in memory final_conversion_img, err := imaging.Decode(conversion_buffer) if err != nil { log.Printf("error decoding buffer to an image in memory: %v", err) return } // save the converted asset to file path imaging.Save(final_conversion_img, "output.jpeg") } // Resize // resize will always run to create new file w/resize (thumbnail) // resize to 160px (standard thumbnail) using imaging.Resize resized_image_160 := imaging.Resize(source_img_data, imageWidth, imageWidth, imaging.Lanczos) // save the image with only the resize operation imaging.Save(resized_image_160, "resized_160.jpeg")
© VincentVanKoh