Created
January 7, 2021 17:36
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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