调整图像大小

时间:2014-04-08 14:55:54

标签: image-processing go

我在这里使用Go resize包: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
    
  4. 如何将数据[]byte转换为---> image.Image并返回---->数据[]byte

4 个答案:

答案 0 :(得分:39)

阅读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, 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

答案 1 :(得分:11)

想要29 times faster吗?请尝试使用惊人的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()
}

答案 2 :(得分:3)

OP 正在使用特定的库/包,但我认为“Go Resizing Images”的问题可以在没有该包的情况下解决。

您可以使用 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)

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

  • draw.NearestNeighbor
    NearestNeighbor 是最近邻插值器。它非常快,但通常会给出非常低质量的结果。放大时,结果将看起来“块状”。

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

  • draw.BiLinear
    BiLinear 是帐篷内核。它很慢,但通常会提供高质量的结果。

  • draw.CatmullRom
    CatmullRom 是 Catmull-Rom 内核。它非常慢,但通常会提供非常高质量的结果。

答案 3 :(得分:2)

您可以使用由bimg(用C编写的快速图像处理库)驱动的libvips

如果您正在寻找图像尺寸调整解决方案即服务,请查看imaginary

相关问题