调整图像大小

huangapple go评论117阅读模式
英文:

Go Resizing Images

问题

你好!要将[]byte转换为image.Image,你可以使用image.Decode()函数。这个函数可以将[]byte解码为image.Image类型。下面是一个示例代码:

  1. import (
  2. "image"
  3. "image/jpeg"
  4. "bytes"
  5. )
  6. // 将 []byte 转换为 image.Image
  7. func bytesToImage(data []byte) (image.Image, error) {
  8. img, _, err := image.Decode(bytes.NewReader(data))
  9. if err != nil {
  10. return nil, err
  11. }
  12. return img, nil
  13. }

要将image.Image转换回[]byte,你可以使用jpeg.Encode()函数将图像编码为JPEG格式。下面是一个示例代码:

  1. import (
  2. "image/jpeg"
  3. "bytes"
  4. )
  5. // 将 image.Image 转换为 []byte
  6. func imageToBytes(img image.Image) ([]byte, error) {
  7. var buf bytes.Buffer
  8. err := jpeg.Encode(&buf, img, nil)
  9. if err != nil {
  10. return nil, err
  11. }
  12. return buf.Bytes(), nil
  13. }

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

I am using the Go resize package here: https://github.com/nfnt/resize

  1. I am pulling an Image from S3, as such:

    1. image_data, err := mybucket.Get(key)
    2. // this gives me data []byte
  2. After that, I need to resize the image:

    1. new_image := resize.Resize(160, 0, original_image, resize.Lanczos3)
    2. // problem is that the original_image has to be of type image.Image
  3. Upload the image to my S3 bucket

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

How do I transform a data []byte to ---> image.Image and back to ----> data []byte?

答案1

得分: 66

阅读 http://golang.org/pkg/image

// 你需要导入image包和一个格式包来进行编码/解码
import (
"bytes"
"image"
"image/jpeg" // 如果你不需要使用jpeg.Encode,可以使用这行代码代替
// _ "image/jpeg"

  1. "github.com/nfnt/resize"

)

// 解码会给你一个Image。
// 如果你已经有一个io.Reader,可以直接将其传递给Decode,而不需要将其读入[]byte。
image, _, err := image.Decode(bytes.NewReader(data))
// 检查错误

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

// Encode使用一个Writer,如果你需要原始的[]byte,可以使用一个Buffer
err = jpeg.Encode(someWriter, newImage, nil)
// 检查错误

英文:

Read http://golang.org/pkg/image

  1. // you need the image package, and a format package for encoding/decoding
  2. import (
  3. "bytes"
  4. "image"
  5. "image/jpeg" // if you don't need to use jpeg.Encode, use this line instead
  6. // _ "image/jpeg"
  7. "github.com/nfnt/resize"
  8. )
  9. // Decoding gives you an Image.
  10. // If you have an io.Reader already, you can give that to Decode
  11. // without reading it into a []byte.
  12. image, _, err := image.Decode(bytes.NewReader(data))
  13. // check err
  14. newImage := resize.Resize(160, 0, original_image, resize.Lanczos3)
  15. // Encode uses a Writer, use a Buffer if you need the raw []byte
  16. err = jpeg.Encode(someWriter, newImage, nil)
  17. // check err

答案2

得分: 42

OP正在使用一个特定的库/包,但我认为“Go调整图像大小”的问题可以在不使用该包的情况下解决。

您可以使用golang.org/x/image/draw来调整图像大小:

  1. input, _ := os.Open("your_image.png")
  2. defer input.Close()
  3. output, _ := os.Create("your_image_resized.png")
  4. defer output.Close()
  5. // 解码图像(从PNG到image.Image):
  6. src, _ := png.Decode(input)
  7. // 设置所需的大小:
  8. dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Max.X/2, src.Bounds().Max.Y/2))
  9. // 调整大小:
  10. draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  11. // 编码到`output`:
  12. png.Encode(output, dst)

在这种情况下,我选择了draw.NearestNeighbor,因为它更快,但效果较差。但还有其他方法,您可以在https://pkg.go.dev/golang.org/x/image/draw#pkg-variables上查看:

  • draw.NearestNeighbor:最近邻插值器。速度非常快,但通常会产生质量很低的结果。放大时,结果会显得“块状”。

  • draw.ApproxBiLinear:最近邻和双线性插值器的混合。速度快,但通常会产生中等质量的结果。

  • draw.BiLinear:帐篷卷积核。速度慢,但通常会产生高质量的结果。

  • draw.CatmullRom:Catmull-Rom卷积核。速度非常慢,但通常会产生非常高质量的结果。

英文:

The OP is using a specific library/package, but I think that the issue of "Go Resizing Images" can be solved without that package.

You can resize de image using golang.org/x/image/draw:

  1. input, _ := os.Open("your_image.png")
  2. defer input.Close()
  3. output, _ := os.Create("your_image_resized.png")
  4. defer output.Close()
  5. // Decode the image (from PNG to image.Image):
  6. src, _ := png.Decode(input)
  7. // Set the expected size that you want:
  8. dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Max.X/2, src.Bounds().Max.Y/2))
  9. // Resize:
  10. draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)
  11. // Encode to `output`:
  12. png.Encode(output, dst)

In that case I choose draw.NearestNeighbor, because it's faster, but looks worse. but there's other methods, you can see on https://pkg.go.dev/golang.org/x/image/draw#pkg-variables:

  • draw.NearestNeighbor
    NearestNeighbor is the nearest neighbor interpolator. It is very fast, but usually gives very low quality results. When scaling up, the result will look 'blocky'.

  • draw.ApproxBiLinear
    ApproxBiLinear is a mixture of the nearest neighbor and bi-linear interpolators. It is fast, but usually gives medium quality results.

  • draw.BiLinear
    BiLinear is the tent kernel. It is slow, but usually gives high quality results.

  • draw.CatmullRom
    CatmullRom is the Catmull-Rom kernel. It is very slow, but usually gives very high quality results.

答案3

得分: 9

想要更快地完成这个任务快29倍吗?试试令人惊叹的vipsthumbnail吧:

  1. sudo apt-get install libvips-tools
  2. vipsthumbnail --help-all

这将调整大小并进行漂亮的裁剪,并将结果保存到文件中:

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

在Go中调用:

  1. func resizeExternally(from string, to string, width uint, height uint) error {
  2. var args = []string{
  3. "--size", strconv.FormatUint(uint64(width), 10) + "x" +
  4. strconv.FormatUint(uint64(height), 10),
  5. "--output", to,
  6. "--crop",
  7. from,
  8. }
  9. path, err := exec.LookPath("vipsthumbnail")
  10. if err != nil {
  11. return err
  12. }
  13. cmd := exec.Command(path, args...)
  14. return cmd.Run()
  15. }
英文:

Want to do it 29 times faster? Try amazing vipsthumbnail instead:

  1. sudo apt-get install libvips-tools
  2. vipsthumbnail --help-all

This will resize and nicely crop saving result to a file:

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

Calling from Go:

  1. func resizeExternally(from string, to string, width uint, height uint) error {
  2. var args = []string{
  3. "--size", strconv.FormatUint(uint64(width), 10) + "x" +
  4. strconv.FormatUint(uint64(height), 10),
  5. "--output", to,
  6. "--crop",
  7. from,
  8. }
  9. path, err := exec.LookPath("vipsthumbnail")
  10. if err != nil {
  11. return err
  12. }
  13. cmd := exec.Command(path, args...)
  14. return cmd.Run()
  15. }

答案4

得分: 5

你可以使用bimg,它由libvips(一个用C编写的快速图像处理库)驱动。

如果你正在寻找一个作为服务的图像调整解决方案,可以看看imaginary

英文:

You could use bimg, which is powered by libvips (a fast image processing library written in C).

If you are looking for a image resizing solution as a service, take a look to imaginary

huangapple
  • 本文由 发表于 2014年4月8日 22:55:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/22940724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定