Golang Converting image.Image to []byte

前端 未结 2 1657
难免孤独
难免孤独 2021-01-31 04:31

Having trouble converting an image.Image to []byte. The problem spot is wrapped in dotted lines.

image_data, err := mybucket.Get(key)

if err != nil {
    panic         


        
相关标签:
2条回答
  • 2021-01-31 04:40

    You want a bytes.Buffer, not a bufio.Writer. bytes.Buffer is used when you need a writer that writes to memory. bufio.Writer just caches data in memory before forwarding it to another writer.

    buf := new(bytes.Buffer)
    err := jpeg.Encode(buf, new_image, nil)
    send_s3 := buf.Bytes()
    
    0 讨论(0)
  • 2021-01-31 04:52

    Adding on to Stephen's code, if you're using the aws s3 go SDK to put an object, your code would look like:

    // create buffer
    buff := new(bytes.Buffer)
    
    // encode image to buffer
    err = png.Encode(buff, new_image)
    if err != nil {
        fmt.Println("failed to create buffer", err)
    }
    
    // convert buffer to reader
    reader := bytes.NewReader(buf.Bytes())
    
    // use it in `PutObjectInput`
    putInput := s3.PutObjectInput{
        Bucket: aws.String("my_bucket"),
        Body:   reader,
    }
    
    // send response
    resp, err := svc.PutObject(&putInput)
    
    0 讨论(0)
提交回复
热议问题