本文整理匯總了Golang中image.DecodeConfig函數的典型用法代碼示例。如果您正苦於以下問題:Golang DecodeConfig函數的具體用法?Golang DecodeConfig怎麽用?Golang DecodeConfig使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了DecodeConfig函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: decode
// decoder reads an image from r and modifies the image as defined by opts.
// swapDimensions indicates the decoded image will be rotated after being
// returned, and when interpreting opts, the post-rotation dimensions should
// be considered.
// The decoded image is returned in im. The registered name of the decoder
// used is returned in format. If the image was not successfully decoded, err
// will be non-nil. If the decoded image was made smaller, needRescale will
// be true.
func decode(r io.Reader, opts *DecodeOpts, swapDimensions bool) (im image.Image, format string, err error, needRescale bool) {
if opts == nil {
// Fall-back to normal decode.
im, format, err = image.Decode(r)
return im, format, err, false
}
var buf bytes.Buffer
tr := io.TeeReader(r, &buf)
ic, format, err := image.DecodeConfig(tr)
if err != nil {
return nil, "", err, false
}
mr := io.MultiReader(&buf, r)
b := image.Rect(0, 0, ic.Width, ic.Height)
sw, sh, needRescale := opts.rescaleDimensions(b, swapDimensions)
if !needRescale {
im, format, err = image.Decode(mr)
return im, format, err, false
}
imageDebug(fmt.Sprintf("Resizing from %dx%d -> %dx%d", ic.Width, ic.Height, sw, sh))
if format == "cr2" {
// Replace mr with an io.Reader to the JPEG thumbnail embedded in a
// CR2 image.
if mr, err = cr2.NewReader(mr); err != nil {
return nil, "", err, false
}
format = "jpeg"
}
if format == "jpeg" && fastjpeg.Available() {
factor := fastjpeg.Factor(ic.Width, ic.Height, sw, sh)
if factor > 1 {
var buf bytes.Buffer
tr := io.TeeReader(mr, &buf)
im, err = fastjpeg.DecodeDownsample(tr, factor)
switch err.(type) {
case fastjpeg.DjpegFailedError:
log.Printf("Retrying with jpeg.Decode, because djpeg failed with: %v", err)
im, err = jpeg.Decode(io.MultiReader(&buf, mr))
case nil:
// fallthrough to rescale() below.
default:
return nil, format, err, false
}
return rescale(im, sw, sh), format, err, true
}
}
// Fall-back to normal decode.
im, format, err = image.Decode(mr)
if err != nil {
return nil, "", err, false
}
return rescale(im, sw, sh), format, err, needRescale
}
示例2: DescribeImage
func DescribeImage(uri string) (mediatype string, width, height int, filelength int64, err error) {
c := curler{
dial_timeo: connection_speedup_timeout,
}
resp, err := c.do_get(uri, nil)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
filelength = int64(-resp.StatusCode)
err = fmt.Errorf("%v: %v", resp.StatusCode, http.StatusText(resp.StatusCode))
return
}
filelength = resp.ContentLength // -1 means unknown
if filelength < 16 && filelength >= 0 {
err = fmt.Errorf("%v: %v", filelength, "content-length insufficient info")
return
}
ct := resp.Header.Get("Content-Type")
mediatype, _, _ = mime.ParseMediaType(ct)
types := strings.Split(mediatype, "/")
if types[0] != "image" {
err = fmt.Errorf("%v: unknown mime %v", uri, mediatype)
return
}
ic, mediatype, err := image.DecodeConfig(resp.Body)
width = ic.Width
height = ic.Height
return
}
示例3: parseImg
func parseImg(raw []byte) (imgInfo, error) {
//fmt.Printf("----------\n")
var info imgInfo
imgConfig, formatname, err := image.DecodeConfig(bytes.NewBuffer(raw))
if err != nil {
return info, err
}
info.formatName = formatname
if formatname == "jpeg" {
err = parseImgJpg(&info, imgConfig)
if err != nil {
return info, err
}
info.data = raw
} else if formatname == "png" {
err = paesePng(raw, &info, imgConfig)
if err != nil {
return info, err
}
}
//fmt.Printf("%#v\n", info)
return info, nil
}
示例4: TestProc
func TestProc(t *testing.T) {
cases := map[*Options]*expected{
&Options{
Format: "jpg",
Quality: 80,
Method: 3,
Base: Construct(new(Source), "http://"+test_server+"/"+file_name).(*Source),
Scale: Construct(new(Scale), "100x").(*Scale),
}: &expected{Size: &PixelDim{100, 75}, ImgType: "jpeg"},
&Options{
Format: "jpg",
Quality: 80,
Base: Construct(new(Source), "http://"+test_server+"/"+file_name).(*Source),
CropRoi: Construct(new(Roi), "1,1,500,500").(*Roi),
Scale: nil,
}: &expected{&PixelDim{500, 500}, "jpeg"},
&Options{
Format: "jpg",
Quality: 80,
Method: 3,
Base: Construct(new(Source), "http://"+test_server+"/"+file_name).(*Source),
Scale: Construct(new(Scale), "100x").(*Scale),
CropRoi: Construct(new(Roi), "center,500,500").(*Roi),
}: &expected{&PixelDim{100, 100}, "jpeg"},
&Options{
Format: "png",
Method: 3,
Base: Construct(new(Source), "http://"+test_server+"/"+file_name).(*Source),
Scale: Construct(new(Scale), "100x").(*Scale),
}: &expected{&PixelDim{100, 75}, "png"},
&Options{
Format: "png",
Method: 3,
Base: Construct(new(Source), "http://"+test_server+"/"+file_name).(*Source),
}: &expected{&PixelDim{1024, 768}, "png"},
}
for option, want := range cases {
b := Do(option)
if b == nil {
t.Errorf("Expected data, result is nil\n")
}
cfg, imgType, err := image.DecodeConfig(bytes.NewReader(b))
if err != nil {
t.Error(err)
}
resultSize := &PixelDim{cfg.Width, cfg.Height}
if !reflect.DeepEqual(resultSize, want.Size) {
t.Errorf("Expected size is %v, got %v\n", want.Size, resultSize)
}
if imgType != want.ImgType {
t.Errorf("Expected image type is %v, got %v", want.ImgType, imgType)
}
}
}
示例5: Config
func (m *markedImage) Config() (image.Config, error) {
cfg, _, err := image.DecodeConfig(bytes.NewReader(m.Img))
if err != nil {
return image.Config{}, e.New(err)
}
return cfg, nil
}
示例6: Config
func (p *photo) Config() (image.Config, error) {
cfg, _, err := image.DecodeConfig(bytes.NewReader(p.Buf))
if err != nil {
return image.Config{}, e.New(err)
}
return cfg, nil
}
示例7: detectFormat
func detectFormat(imgBytes []byte) (string, *serverError) {
_, imgFormat, err := image.DecodeConfig(bytes.NewReader(imgBytes))
if err != nil {
return "", &serverError{fmt.Sprintf("could not detect image format: %s", err), 501}
}
return imgFormat, nil
}
示例8: NewImage
func NewImage(path string) (*Image, error) {
f, ferr := os.Open(path)
if ferr != nil {
fmt.Fprintf(os.Stderr, "%v\n", ferr)
return nil, fmt.Errorf("Could not open image %v", ferr)
}
defer f.Close()
imConf, _, err := image.DecodeConfig(f)
if err != nil {
return nil, fmt.Errorf("Could not decode image", err)
}
im := Image{}
im.Path = path
pathArr := strings.Split(path, "/")
im.Url = "/inc/" + pathArr[len(pathArr)-1]
fmt.Println(im.Url)
size := geom.Rect{}
size.Min = geom.Coord{X: 0, Y: 0}
size.Max = geom.Coord{X: float64(imConf.Width), Y: float64(imConf.Height)}
im.Size = size
return &im, nil
}
示例9: getFileInfo
func getFileInfo(base *url.URL, reader io.Reader) (*result, error) {
h := sha1.New()
buf := make([]byte, 1024)
tee := io.TeeReader(reader, h)
res := result{}
config, format, err := image.DecodeConfig(tee)
if err != nil {
return nil, err
}
res.Width = config.Width
res.Height = config.Height
for ; err != io.EOF; _, err = tee.Read(buf) {
if err != nil {
return nil, err
}
}
hash := base64.RawURLEncoding.EncodeToString(h.Sum(nil))
hashURL, _ := url.Parse(hash + "." + format)
res.URI = base.ResolveReference(hashURL).String()
res.UUID = uuid.NewV5(uuid.NamespaceURL, res.URI)
return &res, nil
}
示例10: HandleUpload
func (c *Single) HandleUpload(avatar []byte) revel.Result {
// Validation rules.
c.Validation.Required(avatar)
c.Validation.MinSize(avatar, 2*KB).
Message("Minimum a file size of 2KB expected")
c.Validation.MaxSize(avatar, 2*MB).
Message("File cannot be larger than 2MB")
// Check format of the file.
conf, format, err := image.DecodeConfig(bytes.NewReader(avatar))
c.Validation.Required(err == nil).Key("avatar").
Message("Incorrect file format")
c.Validation.Required(format == "jpeg" || format == "png").Key("avatar").
Message("JPEG or PNG file format is expected")
// Check resolution.
c.Validation.Required(conf.Height >= 150 && conf.Width >= 150).Key("avatar").
Message("Minimum allowed resolution is 150x150px")
// Handle errors.
if c.Validation.HasErrors() {
c.Validation.Keep()
c.FlashParams()
return c.Redirect(routes.Single.Upload())
}
return c.RenderJson(FileInfo{
ContentType: c.Params.Files["avatar"][0].Header.Get("Content-Type"),
Filename: c.Params.Files["avatar"][0].Filename,
RealFormat: format,
Resolution: fmt.Sprintf("%dx%d", conf.Width, conf.Height),
Size: len(avatar),
Status: "Successfully uploaded",
})
}
示例11: Get
// Get implements Server
func (srv *DecodeCheckServer) Get(params imageserver.Params) (*imageserver.Image, error) {
im, err := srv.Server.Get(params)
if err != nil {
return nil, err
}
if srv.PreDecode != nil {
err = srv.PreDecode(im, params)
if err != nil {
return nil, err
}
}
cfg, format, err := image.DecodeConfig(bytes.NewReader(im.Data))
if err != nil {
return nil, &imageserver.ImageError{Message: err.Error()}
}
if format != im.Format {
return nil, &imageserver.ImageError{Message: fmt.Sprintf("decoded format \"%s\" does not match image format \"%s\"", format, im.Format)}
}
if srv.PostDecode != nil {
err = srv.PostDecode(cfg, format, params)
if err != nil {
return nil, err
}
}
return im, err
}
示例12: sizer
func sizer(originalTag string) string {
tag := originalTag
if strings.Index(tag, widthAttr) > -1 &&
strings.Index(tag, heightAttr) > -1 {
return tag // width & height attributes are already present
}
match := srcRx.FindStringSubmatch(tag)
if match == nil {
fmt.Println("can't find <img>'s src attribute", tag)
return tag
}
file, err := os.Open(match[1])
if err != nil {
fmt.Println("can't open image to read its size:", err)
return tag
}
defer file.Close()
config, _, err := image.DecodeConfig(file)
if err != nil {
fmt.Println("can't ascertain the image's size:", err)
return tag
}
tag, end := tagEnd(tag)
if strings.Index(tag, widthAttr) == -1 {
tag += fmt.Sprintf(` %s"%d"`, widthAttr, config.Width)
}
if strings.Index(tag, heightAttr) == -1 {
tag += fmt.Sprintf(` %s"%d"`, heightAttr, config.Height)
}
tag += end
return tag
}
示例13: LoadFromPath
func (m *Manager) LoadFromPath(path string) *Data {
setupTextureList()
m.mutex.RLock()
var data *Data
var ok bool
if data, ok = m.registry[path]; ok {
m.mutex.RUnlock()
m.mutex.Lock()
data.accessed = generation
m.mutex.Unlock()
return data
}
m.mutex.RUnlock()
m.mutex.Lock()
if data, ok = m.deleted[path]; ok {
delete(m.deleted, path)
} else {
data = &Data{}
}
data.accessed = generation
m.registry[path] = data
m.mutex.Unlock()
f, err := os.Open(path)
if err != nil {
return data
}
config, _, err := image.DecodeConfig(f)
f.Close()
data.dx = config.Width
data.dy = config.Height
load_requests <- loadRequest{path, data}
return data
}
示例14: load
// Slower operations to fill props struct
func (p *props) load(h hash.Hash, name string) *props {
p.mime = mime.TypeByExtension(p.ext)
r, err := os.Open(name)
if err != nil {
log.Print(name, ": Props: ", err)
return p
}
defer r.Close()
p.ftype = mapType(p.mime)
// TODO: this is quite unreadable
copy(p.chash[:], filehash(name, h, r))
copy(p.dident[:], strhash(p.dir, h))
// If the extension is empty, we need to detect
// the MIME type via file contents
if p.mime == "" {
p.mime = sniffMIME(name, r)
}
// Non-images are completely processed at this point
if !strings.HasPrefix(p.mime, "image/") {
return p
}
// Image-specific processing
if _, err := r.Seek(0, 0); err != nil {
log.Print(name, ": Seek: ", err)
return p
}
imgconf, _, err := image.DecodeConfig(r)
if err != nil {
log.Print(name, ": Image decoder: ", err)
return p
}
p.isize = image.Point{imgconf.Width, imgconf.Height}
return p
}
示例15: Parse
// Parse parses an url and returns structurized representation
func (p *Parser) Parse(u string) *oembed.Info {
if p.client == nil {
transport := &http.Transport{DisableKeepAlives: true, Dial: p.Dial}
p.client = &http.Client{Timeout: p.WaitTimeout, Transport: transport, CheckRedirect: p.skipRedirectIfFoundOembed}
}
p.fetchURLCalls = 0
info := p.parseOembed(u)
// and now we try to set missing image sizes
if info != nil {
width := info.ThumbnailWidth
if len(info.ThumbnailURL) > 0 && width == 0 {
p.fetchURLCalls = 0
data, newURL, _, err := p.fetchURL(info.ThumbnailURL)
if err == nil {
info.ThumbnailURL = newURL
config, _, err := image.DecodeConfig(bytes.NewReader(data))
if err == nil {
info.ThumbnailWidth = uint64(config.Width)
info.ThumbnailHeight = uint64(config.Height)
}
}
}
}
return info
}