Example #1
0
// TransferUrl 将外站图片URL转为本站,如果失败,返回原图
func (this *UploaderLogic) TransferUrl(ctx context.Context, origUrl string, prefixs ...string) (string, error) {
	if origUrl == "" || strings.Contains(origUrl, "studygolang") {
		return origUrl, errors.New("origin image is empty or is studygolang.com")
	}

	resp, err := http.Get(origUrl)
	if err != nil {
		return origUrl, errors.New("获取图片失败")
	}
	defer resp.Body.Close()

	buf, _ := ioutil.ReadAll(resp.Body)

	md5 := goutils.Md5Buf(buf)
	objImage, err := this.findImage(md5)
	if err != nil {
		logger.Errorln("find image:", md5, "error:", err)
		return origUrl, err
	}

	if objImage.Pid > 0 {
		return objImage.Path, nil
	}

	ext := filepath.Ext(origUrl)
	if ext == "" {
		contentType := http.DetectContentType(buf)
		exts, _ := mime.ExtensionsByType(contentType)
		if len(exts) > 0 {
			ext = exts[0]
		}
	}

	prefix := times.Format("ymd")
	if len(prefixs) > 0 {
		prefix = prefixs[0]
	}
	path := prefix + "/" + md5 + ext
	reader := bytes.NewReader(buf)

	if len(buf) > MaxImageSize {
		return origUrl, errors.New("文件太大")
	}

	err = this.uploadMemoryFile(reader, path)
	if err != nil {
		return origUrl, err
	}

	go this.saveImage(buf, path)

	return path, nil
}
Example #2
0
func (this *UploaderLogic) saveImage(buf []byte, path string) {
	objImage := &model.Image{
		Path: path,
		Md5:  goutils.Md5Buf(buf),
		Size: len(buf),
	}

	reader := bytes.NewReader(buf)
	img, _, err := image.Decode(reader)
	if err != nil {
		logger.Errorln("image decode err:", err)
	} else {
		objImage.Width = img.Bounds().Dx()
		objImage.Height = img.Bounds().Dy()
	}

	_, err = MasterDB.Insert(objImage)
	if err != nil {
		logger.Errorln("image insert err:", err)
	}
}
Example #3
0
func (this *UploaderLogic) UploadImage(ctx context.Context, reader gio.Reader, imgDir string, buf []byte, ext string) (string, error) {
	objLogger := GetLogger(ctx)

	md5 := goutils.Md5Buf(buf)
	objImage, err := this.findImage(md5)
	if err != nil {
		objLogger.Errorln("find image:", md5, "error:", err)
		return "", err
	}

	if objImage.Pid > 0 {
		return objImage.Path, nil
	}

	path := imgDir + "/" + md5 + ext
	if err = this.uploadMemoryFile(reader, path); err != nil {
		return "", err
	}

	go this.saveImage(buf, path)

	return path, nil
}