Skip to content

Instantly share code, notes, and snippets.

@julianfbeck
Created January 7, 2021 17:36
Show Gist options
  • Select an option

  • Save julianfbeck/3f168d31052f762ce788daf2c9cdb46b to your computer and use it in GitHub Desktop.

Select an option

Save julianfbeck/3f168d31052f762ce788daf2c9cdb46b to your computer and use it in GitHub Desktop.
Use first 512 bytes of the file to check if an Image is a Jpeg or PNG. Decode and load into channel
func loadImageChannel(pathPicture string, images chan image.Image, errors chan error) {
file, err := os.Open(pathPicture)
if err != nil {
log.Fatalf("failed to open: %s", err)
}
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil {
errors <- err
}
// Reset the read pointer if necessary.
file.Seek(0, 0)
contentType := http.DetectContentType(buffer)
switch contentType {
case "image/png":
im, err := png.Decode(file)
if err != nil {
log.Fatalf("failed to decode: %s", err)
}
if err == nil {
images <- im
} else {
errors <- err
}
case "image/jpeg":
im, err := jpeg.Decode(file)
if err != nil {
log.Fatalf("failed to decode: %s", err)
}
if err == nil {
images <- im
} else {
errors <- err
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment