func Fuzz(data []byte) int { cfg, err := jpeg.DecodeConfig(bytes.NewReader(data)) if err != nil { return 0 } if cfg.Width*cfg.Height > 1e6 { return 0 } img, err := jpeg.Decode(bytes.NewReader(data)) if err != nil { return 0 } for q := 0; q <= 100; q += 10 { var w bytes.Buffer err = jpeg.Encode(&w, img, &jpeg.Options{q}) if err != nil { panic(err) } img1, err := jpeg.Decode(&w) if err != nil { panic(err) } if !reflect.DeepEqual(img.Bounds(), img1.Bounds()) { panic("bounds changed") } } return 1 }
func checkRes(url string, i int, wg *sync.WaitGroup, iron *Config, result *Result) { defer wg.Done() start := time.Now() fmt.Println("Getting image...", i) resp, err := http.Get(url) defer resp.Body.Close() if err != nil { panic("Failed to get image from URL given") } elapsed := time.Since(start) fmt.Printf("Took %s GET for image %d\n", elapsed, i) fmt.Println("Decoding...", i) config, err := jpeg.DecodeConfig(resp.Body) if err != nil { fmt.Println("Invalid JPEG...", i) } // Collect results if config.Width >= iron.Validation.Width && config.Height >= iron.Validation.Height { result.Images = append(result.Images, Image{url, true}) } else { result.Images = append(result.Images, Image{url, false}) } }
func imageMeta(r io.ReadSeeker) (*Image, error) { conf, err := jpeg.DecodeConfig(r) if err != nil { return nil, fmt.Errorf("cannot decode JPEG: %s", err) } // compute image hash from image content oid := sha256.New() if _, err := io.Copy(oid, r); err != nil { return nil, fmt.Errorf("cannot compute SHA: %s", err) } img := Image{ ImageID: encode(oid), Width: conf.Width, Height: conf.Height, } if _, err := r.Seek(0, os.SEEK_SET); err != nil { return nil, fmt.Errorf("cannot seek: %s", err) } if meta, err := exif.Decode(r); err != nil { log.Error("cannot extract EXIF metadata", "error", err.Error()) } else { if orientation, err := meta.Get(exif.Orientation); err != nil { log.Debug("cannot extract image orientation", "decoder", "EXIF", "error", err.Error()) } else { if o, err := orientation.Int(0); err != nil { log.Debug("cannot format orientation", "decoder", "EXIF", "error", err.Error()) } else { img.Orientation = o } } if dt, err := meta.Get(exif.DateTimeOriginal); err != nil { log.Debug("cannot extract image datetime original", "decoder", "EXIF", "error", err.Error()) } else { if raw, err := dt.StringVal(); err != nil { log.Debug("cannot format datetime original", "decoder", "EXIF", "error", err.Error()) } else { img.Created, err = time.Parse("2006:01:02 15:04:05", raw) if err != nil { log.Debug("cannot parse datetime original", "decoder", "EXIF", "value", raw, "error", err.Error()) } } } } return &img, nil }
func parseJPEG(r io.Reader) (int, int, error) { cfg, err := jpeg.DecodeConfig(r) if err != nil { return 0, 0, err } return cfg.Width, cfg.Height, nil }
func validJPEGFile(fn string) bool { jpegImage, err := os.Open(fn) check(err) defer jpegImage.Close() _, err = jpeg.DecodeConfig(jpegImage) if err != nil { return false } return true }
func decodeJPEG(f multipart.File) (*Image, error) { var image Image ic, err := jpeg.DecodeConfig(f) _, err = f.Seek(0, 0) i, err := jpeg.Decode(f) if err != nil { return nil, fmt.Errorf("Could not decode JPEG file.") } image.Config = ic image.Image = i return &image, nil }
func visit(path string, f os.FileInfo, err error) error { i, ierr := os.Open(path) defer i.Close() if ierr != nil { return err } // check if file jpg or png // get dimensions of images // lowres images to other directory and highres to another switch strings.ToLower(filepath.Ext(path)) { case ".jpg", ".jpeg": j, jerr := jpeg.DecodeConfig(i) i.Close() if jerr != nil { return jerr } v, fname := validateResolution(j), f.Name() err := move(path, fname, v) if err != nil { fmt.Println(err) } return nil case ".png": p, perr := png.DecodeConfig(i) i.Close() if perr != nil { return perr } v, fname := validateResolution(p), f.Name() err := move(path, fname, v) if err != nil { fmt.Println(err) } return nil } return nil }
func (this *UploadedFile) Dimensions() (int, int, error) { f, err := os.Open(this.path) if err != nil { return 0, 0, err } var cfg image.Config switch true { case this.IsGif(): cfg, err = gif.DecodeConfig(f) case this.IsPng(): cfg, err = png.DecodeConfig(f) case this.IsJpeg(): cfg, err = jpeg.DecodeConfig(f) default: return 0, 0, errors.New("Invalid mime type!") } if err != nil { return 0, 0, err } return cfg.Width, cfg.Height, nil }
func UploadHandler(conn *rtgo.Conn, data []byte, msg *rtgo.Message) { schema := make(map[string]interface{}) err := json.Unmarshal(msg.Payload, &schema) if err != nil { log.Println(err) return } topic := schema["topic"].(string) now := time.Now() schema["timestamp"] = fmt.Sprintf("%d/%d/%d(%s)%d:%d:%d", now.Month(), now.Day(), now.Year(), now.Weekday().String()[:3], now.Hour(), now.Minute(), now.Second()) schema["uuid"] = uuid.NewV4().String() hash := fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%s%s", schema["timestamp"], schema["uuid"]))))[:9] schema["hash"] = hash if file, ok := schema["file"].(string); ok { file_path := fmt.Sprintf("./static/images/uploads/%s", schema["file_name"]) fdata, err := dataurl.DecodeString(file) if err != nil { log.Println(err) return } ioutil.WriteFile(file_path, fdata.Data, 0775) saved_file, err := os.Open(file_path) if err != nil { log.Println(err) return } var config image.Config if schema["file_mime"] == "image/jpeg" { config, err = jpeg.DecodeConfig(saved_file) } else if schema["file_mime"] == "image/png" { config, err = png.DecodeConfig(saved_file) } else if schema["file_mime"] == "image/gif" { config, err = gif.DecodeConfig(saved_file) } schema["file_dimensions"] = fmt.Sprintf("%dx%d", config.Width, config.Height) delete(schema, "file") } if schema["type"] == "thread" { if err := app.DB.InsertObj(topic, hash, schema); err != nil { return } } else if schema["type"] == "reply" { thread := schema["thread"].(string) if obj, err := app.DB.GetObj(topic, thread); err == nil { thisobj := obj.(map[string]interface{}) replies := thisobj["replies"].(map[string]interface{}) replies[hash] = schema tagging := schema["tagging"].([]interface{}) for _, tag := range tagging { if tag.(string) == thread { thisobj["taggedBy"] = append(thisobj["taggedBy"].([]interface{}), hash) } else if _, ok := replies[tag.(string)]; ok { reply := replies[tag.(string)].(map[string]interface{}) reply["taggedBy"] = append(reply["taggedBy"].([]interface{}), hash) } } if err := app.DB.InsertObj(topic, thread, thisobj); err != nil { log.Println(err) return } } else { log.Println(err) return } } payload, err := json.Marshal(&schema) if err != nil { log.Println(err) return } response := &rtgo.Message{ RoomLength: len(schema["topic"].(string)), Room: schema["topic"].(string), EventLength: len("new-" + schema["type"].(string)), Event: "new-" + schema["type"].(string), DstLength: 0, Dst: "", SrcLength: len(conn.Id), Src: conn.Id, PayloadLength: len(payload), Payload: payload, } binary_response := rtgo.MessageToBytes(response) conn.Emit(binary_response, response) conn.Send <- binary_response }
//This function is going to be the core of my scanner. func (p *JpegPhoto) Inspect(f io.ReadSeeker) (item *core.Item, err error) { item = &core.Item{ Type: core.ItemTypePhoto, Location: &core.LatLon{}, } p.Width = 0 p.Height = 0 p.Orientation = OrientedNormal p.Device = "" cfg, err := jpeg.DecodeConfig(f) if err != nil { return nil, err } p.Width = cfg.Width p.Height = cfg.Height f.Seek(0, 0) //rewind... //get date from exif exifInfo, err := exif.Decode(f) if err != nil { return nil, err //no exif, no photo } var createds []time.Time for _, field := range possibleExifDateTimeFields { tag, err := exifInfo.Get(field) if err != nil { //log.Println("no tag", field) continue } tag_val, err := tag.StringVal() if err != nil { log.Println("wrong type", field) continue } if tag_created, err := time.Parse(ExifDateFormat, tag_val); err == nil { if tag_created == exifDateBug { log.Println("EXIF DATE BUG:", field) continue } createds = append(createds, tag_created) } } if len(createds) == 0 || createds[0].IsZero() { return nil, fmt.Errorf("Could not get date photo taken") } item.Created = core.AdjustTime(createds[0]) //now optional, orientation tag, err := exifInfo.Get(exif.Orientation) if err == nil { o, _ := tag.Int(0) p.Orientation = ExifOrientation(o) //swap height/width if needed. switch p.Orientation { case OrientedMirror270, OrientedNormal270, OrientedNormal90, OrientedMirror90: p.Width, p.Height = p.Height, p.Width } } //Device/Make tag, err = exifInfo.Get(exif.Make) if err == nil && tag.Format() == tiff.StringVal { p.Device, _ = tag.StringVal() } tag, err = exifInfo.Get(exif.Model) if err == nil && tag.Format() == tiff.StringVal { if p.Device == "" { p.Device, _ = tag.StringVal() } else { tag_val, _ := tag.StringVal() p.Device = p.Device + " " + tag_val } } //and GPS location setLocationFromExif(item.Location, exifInfo) //get size of file by seeking to the end. p.Size, _ = f.Seek(0, 2) b, err := json.Marshal(p) if err != nil { return nil, err } //now add meta to item. item.Meta = json.RawMessage(b) return }
func _decode_album(src string) (Album, Album) { photoList, _ := filepath.Glob(src + "\\*") var album Album var albumSummary Album var imgInfo image.Config var comment_str string decoder := mahonia.NewDecoder("UTF-16LE") for key := range photoList { fullFileName := photoList[key] //读取图片长宽等信息 photo_fi, err := os.Open(fullFileName) if err != nil { log.Fatal(err) } defer photo_fi.Close() switch strings.ToLower(path.Ext(fullFileName)) { case ".jpg", ".jpeg": imgInfo, err = jpeg.DecodeConfig(photo_fi) if err != nil { fmt.Println("图片解析错误:" + fullFileName) os.Exit(0) } case ".png": imgInfo, err = png.DecodeConfig(photo_fi) if err != nil { fmt.Println("图片解析错误:" + fullFileName) os.Exit(0) } case ".gif": imgInfo, err = gif.DecodeConfig(photo_fi) if err != nil { fmt.Println("图片解析错误:" + fullFileName) os.Exit(0) } default: continue } //读取图片评注信息 photo_fi, err = os.Open(fullFileName) if err != nil { log.Fatal(err) } photo_exif, err := exif.Decode(photo_fi) if err != nil { comment_str = "" } else { comment, err := photo_exif.Get(exif.UserComment) if err != nil { comment_str = "" } else { comment_str = decoder.CConvertString(comment.Val) } } photo_fi.Close() var bigPhotoFileName, photoFileName string photoFileName = filepath.Base(fullFileName) if strings.ToLower(path.Ext(fullFileName)) == ".gif" || imgInfo.Width < siteInfo.ImgWidth { //global var : SiteInfo bigPhotoFileName = photoFileName } else { bigPhotoFileName = "big_" + photoFileName } //追加图片信息 var photo = Photo{Src: fullFileName, Comment: comment_str, Width: imgInfo.Width, Height: imgInfo.Height, PhotoFileName: photoFileName, BigPhotoFileName: bigPhotoFileName} album = append(album, photo) if strings.HasPrefix(filepath.Base(fullFileName), "~") { albumSummary = append(albumSummary, photo) } } return album, albumSummary }