2014-04-08 3 views
15

내가 여기에 이동, 크기 조정 패키지를 사용하고 있습니다 : 같은 https://github.com/nfnt/resize이동 크기 조정 이미지

1) 나는 S3에서 이미지를 당기는 오전 :

 image_data, err := mybucket.Get(key) 
     // this gives me data []byte 

2) 그 후, 나는 크기를 조정해야 이미지 :

 new_image := resize.Resize(160, 0, original_image, resize.Lanczos3) 
     // problem is that the original_image has to be of type image.Image 

3) 내 S3 버킷에 이미지를 업로드

 err : = mybucket.Put('newpath', new_image, 'image/jpg', 'aclstring') 
    // problem is that new image needs to be data []byte 

어떻게 데이터 [] 바이트를 ---> 이미지로 변환합니까? 이미지 및 이미지 데이터로 돌아 가기 ----> 데이터 [] 바이트 ??

미리 도움을 청하십시오!

답변

32

// you need the image package, and a format package for encoding/decoding 
import (
    "bytes" 
    "image" 
    "image/jpeg" 

    // if you don't need to use jpeg.Encode, import like so: 
    // _ "image/jpeg" 
) 

// Decoding gives you an Image. 
// If you have an io.Reader already, you can give that to Decode 
// without reading it into a []byte. 
image, _, err := image.Decode(bytes.NewReader(data)) 
// check err 

newImage := resize.Resize(160, 0, original_image, resize.Lanczos3) 

// Encode uses a Writer, use a Buffer if you need the raw []byte 
err = jpeg.Encode(someWriter, newImage, nil) 
// check err 
+0

최고에 봐. "image/jpeg"앞에 밑줄은 무엇입니까? 또한 바이트 변수를 어떻게 사용할 수 있습니까? 마지막으로 [] 바이트로 다시 인코딩하는 방법은 무엇입니까? 고마워요 –

+3

밑줄은 부작용 (이 경우에는 디코더 등록)을 위해서만 무언가를 가져 오는 방법입니다. 'jpeg.Encode'를 사용하려면 밑줄을 사용하지 않고 가져 오기하십시오. 'bytes'는 표준 라이브러리의 패키지입니다. – JimB

9

그것을 29 times faster를 원하십니까 http://golang.org/pkg/image 읽기? 놀라운 vipsthumbnail 대신보십시오 :

sudo apt-get install libvips-tools 
vipsthumbnail --help-all 

이 크기를 조정하고 멋지게 파일에 결과를 저장 자르기 :

vipsthumbnail original.jpg -s 700x200 -o 700x200.jpg -c 

에서 이동 전화 :

func resizeExternally(from string, to string, width uint, height uint) error { 
    var args = []string{ 
     "--size", strconv.FormatUint(uint64(width), 10) + "x" + 
      strconv.FormatUint(uint64(height), 10), 
     "--output", to, 
     "--crop", 
     from, 
    } 
    path, err := exec.LookPath("vipsthumbnail") 
    if err != nil { 
     return err 
    } 
    cmd := exec.Command(path, args...) 
    return cmd.Run() 
} 
+3

시스템 호출이 바람직하지 않은 경우 [바인딩] (https://github.com/DAddYE/vips)도 있습니다. – transistor09

2

당신은 bimg을 사용할 수, 전원 libvips (C로 작성된 빠른 이미지 처리 라이브러리).

하는 서비스로 솔루션을 크기 조정 이미지를 찾고 있다면, imaginary