调整图像大小

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

Go Resizing Images

问题

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

import (
    "image"
    "image/jpeg"
    "bytes"
)

// 将 []byte 转换为 image.Image
func bytesToImage(data []byte) (image.Image, error) {
    img, _, err := image.Decode(bytes.NewReader(data))
    if err != nil {
        return nil, err
    }
    return img, nil
}

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

import (
    "image/jpeg"
    "bytes"
)

// 将 image.Image 转换为 []byte
func imageToBytes(img image.Image) ([]byte, error) {
    var buf bytes.Buffer
    err := jpeg.Encode(&buf, img, nil)
    if err != nil {
        return nil, err
    }
    return buf.Bytes(), nil
}

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

英文:

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

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

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

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

     err : = mybucket.Put('newpath', new_image, 'image/jpg', 'aclstring')
     // 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"

"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

// 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, use this line instead 
	// _ "image/jpeg"

    "github.com/nfnt/resize"

    
)

// 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

答案2

得分: 42

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

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

input, _ := os.Open("your_image.png")
defer input.Close()

output, _ := os.Create("your_image_resized.png")
defer output.Close()

// 解码图像(从PNG到image.Image):
src, _ := png.Decode(input)

// 设置所需的大小:
dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Max.X/2, src.Bounds().Max.Y/2))

// 调整大小:
draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)

// 编码到`output`:
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:

input, _ := os.Open("your_image.png")
defer input.Close()

output, _ := os.Create("your_image_resized.png")
defer output.Close()

// Decode the image (from PNG to image.Image):
src, _ := png.Decode(input)

// Set the expected size that you want:
dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Max.X/2, src.Bounds().Max.Y/2))

// Resize:
draw.NearestNeighbor.Scale(dst, dst.Rect, src, src.Bounds(), draw.Over, nil)

// Encode to `output`:		
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吧:

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

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

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

在Go中调用:

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()
}
英文:

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

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

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

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

Calling from Go:

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()
}

答案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:

确定