Pure golang image resizing

This package is no longer being updated! Please look for alternatives if that bothers you.

Resize

Image resizing for the Go programming language with common interpolation methods.

Build Status

Installation

$ go get github.com/nfnt/resize

It's that easy!

Usage

This package needs at least Go 1.1. Import package with

import "github.com/nfnt/resize"

The resize package provides 2 functions:

  • resize.Resize creates a scaled image with new dimensions (width, height) using the interpolation function interp. If either width or height is set to 0, it will be set to an aspect ratio preserving value.
  • resize.Thumbnail downscales an image preserving its aspect ratio to the maximum dimensions (maxWidth, maxHeight). It will return the original image if original sizes are smaller than the provided dimensions.
resize.Resize(width, height uint, img image.Image, interp resize.InterpolationFunction) image.Image
resize.Thumbnail(maxWidth, maxHeight uint, img image.Image, interp resize.InterpolationFunction) image.Image

The provided interpolation functions are (from fast to slow execution time)

Which of these methods gives the best results depends on your use case.

Sample usage:

package main

import (
	"github.com/nfnt/resize"
	"image/jpeg"
	"log"
	"os"
)

func main() {
	// open "test.jpg"
	file, err := os.Open("test.jpg")
	if err != nil {
		log.Fatal(err)
	}

	// decode jpeg into image.Image
	img, err := jpeg.Decode(file)
	if err != nil {
		log.Fatal(err)
	}
	file.Close()

	// resize to width 1000 using Lanczos resampling
	// and preserve aspect ratio
	m := resize.Resize(1000, 0, img, resize.Lanczos3)

	out, err := os.Create("test_resized.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()

	// write new image to file
	jpeg.Encode(out, m, nil)
}

Caveats

  • Optimized access routines are used for image.RGBA, image.NRGBA, image.RGBA64, image.NRGBA64, image.YCbCr, image.Gray, and image.Gray16 types. All other image types are accessed in a generic way that will result in slow processing speed.
  • JPEG images are stored in image.YCbCr. This image format stores data in a way that will decrease processing speed. A resize may be up to 2 times slower than with image.RGBA.

Downsizing Samples

Downsizing is not as simple as it might look like. Images have to be filtered before they are scaled down, otherwise aliasing might occur. Filtering is highly subjective: Applying too much will blur the whole image, too little will make aliasing become apparent. Resize tries to provide sane defaults that should suffice in most cases.

Artificial sample

Original image Rings


Nearest-Neighbor

Bilinear

Bicubic

Mitchell-Netravali

Lanczos2

Lanczos3

Real-Life sample

Original image
Original


Nearest-Neighbor

Bilinear

Bicubic

Mitchell-Netravali

Lanczos2

Lanczos3

License

Copyright (c) 2012 Jan Schlicht [email protected] Resize is released under a MIT style license.

Owner
Jan Schlicht
Distributed systems expert, building solutions for the cloud with @kubernetes and @mesos.
Jan Schlicht
Comments
  • crash in resize

    crash in resize

    Unfortunately I don't have access to image that caused the crash and don't know what was its size and what was the destination size. It could be related to some boundary conditions (very small source or very small destination size).

    But this happened using the latest resize (ccddecd1bf0b15e36e2ffcfdef7c6832eaa0dbf6):

    panic: runtime error: slice bounds out of range
    
    goroutine 574 [running]:
    runtime.panic(0x914ac0, 0xc524af)
        /usr/local/Cellar/go/1.3/libexec/src/pkg/runtime/panic.c:279 +0xf5
    github.com/nfnt/resize.resizeRGBA(0xc208256440, 0xc208256700, 0x3fff7b03531dec0d, 0xc20808a500, 0x268, 0x268, 0xc20808aa00, 0x9a, 0x9a, 0x4)
        /var/folders/9t/62vbwdb93rg3tpvsy6y30tzh0000gn/T/godep/rev/cc/ddecd1bf0b15e36e2ffcfdef7c6832eaa0dbf6/src/github.com/nfnt/resize/converter.go:98 +0x5b3
    github.com/nfnt/resize.func·001()
        /var/folders/9t/62vbwdb93rg3tpvsy6y30tzh0000gn/T/godep/rev/cc/ddecd1bf0b15e36e2ffcfdef7c6832eaa0dbf6/src/github.com/nfnt/resize/resize.go:112 +0xcb
    created by github.com/nfnt/resize.Resize
        /var/folders/9t/62vbwdb93rg3tpvsy6y30tzh0000gn/T/godep/rev/cc/ddecd1bf0b15e36e2ffcfdef7c6832eaa0dbf6/src/github.com/nfnt/resize/resize.go:113 +0x27bc
    

    This corresponds to the crash at the last line of this:

    
    func resizeRGBA(in *image.RGBA, out *image.RGBA, scale float64, coeffs []int16, offset []int, filterLength int) {
        oldBounds := in.Bounds()
        newBounds := out.Bounds()
        minX := oldBounds.Min.X * 4
        maxX := (oldBounds.Max.X - oldBounds.Min.X - 1) * 4
    
        for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
            row := in.Pix[(x-oldBounds.Min.Y)*in.Stride:]
    

    This is on a 24-core amd64 ubuntu 12.4 box, go 1.3.

    On a related note: it would be good to have an option to disable internal nfnt threading (i.e. make it do the resize using a single, current goroutine) so that it's possible to catch and recover from crashes in nfnt with recover(). Imagine a server application that does image resizing - if a crash in nfnt happens on some random goroutine, it'll crash the whole server. If it happens on current goroutine, I can write a wrapper that will recover() from the panic().

  • Resizing seems to cause artifacts.

    Resizing seems to cause artifacts.

    Here is an image resized with nfnt/resize on the left, and imagemagick on the right (using resize_to_fit from rmagick which should fallback to a resize using Lanczos followed by a crop).

    Edit: I've tried multiple filters and they all seem to have this issue of making these lines. The one in the picture is from Lanczos 3.

    I'm not sure what to make of it, only that it appears to have a lot of artifacts (scanlines?) in the one created by this package. Could be something I'm doing but all I do is use image.Draw to translate & crop.

    2014-09-04-131125_1267x929_scrot

  • support YCbCr subsample ratios 4:1:0 and 4:1:1

    support YCbCr subsample ratios 4:1:0 and 4:1:1

    See also #37 and #39.

    This fixes a panic() for a few JPEG images found in the wild. Without this fix, a program which downloads and resizes tons of images from a source like ImageNet will eventually panic unexpectedly upon finding a 4:1:0 or 4:1:1 image.

    To test this change, I have attached a 4:1:0 image found in the wild (from ImageNet, in fact). I zipped the image to prevent any potential image compression from Github (which would presumably destroy the 4:1:0-ness of the image).

    YCbCr_410.jpg.zip

    I could not find a 4:1:1 in the wild (although I only searched for several minutes). To address this, I have attached a small Go program which can convert an image in-memory to a 4:1:1 image, then resize said image. I could not use this program to generate a 4:1:1 image file because Go's jpeg package converts 4:1:1 into 4:2:0 (as of Go 1.7)

    411_test.go.zip

  • is this speed normal?

    is this speed normal?

    hi, I'm using your lib to resize my photo. It seem consume too much time for one photo.

    I'm using NearestNeighbor method. my photo is about 5Mbyte. here is my code: https://gist.github.com/ifq/6268096 and the result for resize one photo is:

    $ ./resize ~/tmp/testimg/2012-08-26/IMGA0598.JPG 
    time consumed sub:  0 6525402249
    time consumed sub:  1 7193831897
    time consumed:  14912730741
    

    my laptop is i7, 8G memory. host OS win7 32bit, VM OS is linux mint inside virtualbox with 4G memory.

    If it's normal performance of this lib, do you planing only performance improvement?

  • Resize artifacts

    Resize artifacts

    Thank you for this package. I downsized this image https://www.dropbox.com/s/fs91vfx1y4khymv/button_cost_up.png?dl=0 and got artifacts https://www.dropbox.com/s/0me0559p7nl3yf5/test_resized.png?dl=0

    with all interpolations except NearestNeighbor. How to avoid it?

  • Panic on Resize

    Panic on Resize

    Hi,

    we get this issue when resizing some user-supplied pictures.

    And no, unfortunately I can't provide any sample pics. I'll try to get one.

    goroutine 5456 [running]:
    panic(0xc34040, 0xc42000c0c0)
            /usr/local/go/src/runtime/panic.go:500 +0x1a1
    github.com/nfnt/resize.resizeRGBA(0xc4203e4c40, 0xc4203e58c0, 0x0, 0xc422c18000, 0x1944, 0x1944, 0x
            github.com/nfnt/resize/converter.go:119 +0x44d
    github.com/nfnt/resize.Resize.func2(0xc420610140, 0xc4203e4c40, 0xc4203e58c0, 0x0, 0xc4205900a0, 0x
            github.com/nfnt/resize/resize.go:130 +0xc5
    created by github.com/nfnt/resize.Resize
           github.com/nfnt/resize/resize.go:131 +0x345b
    
  • Don't reverse alpha premultiplication, it's fundamentally wrong

    Don't reverse alpha premultiplication, it's fundamentally wrong

    I have looked at your code and that's what I have to say: you are fundamentally wrong in dealing with alpha-premultiplied images. Alpha premultiplication was introduced to eliminate interpolation error on images with alpha channel. If image is not premultiplied you shoud premultipy it first before interpolation. Your code does opposite. https://en.wikipedia.org/wiki/Alpha_compositing#Description

  • Add: thumbnail helper function

    Add: thumbnail helper function

    Hi,

    I added thumbnail helper function so that if someone simply want to create thumbnails he don't need to reinvent the wheel every time.

    I have one question about behaviour:

    • Python PIL thumbnail method process images even if they are smaller than max provided sizes (resize them to same size) and don't process images only if file sizes are same as max provided sizes.
    • I made this method to not process images if they sizes are same or smaller than max provided sizes.

    Which approach do you prefer?

    Best regards, Dobrosław Żybort

  • Wrong colors after resize

    Wrong colors after resize

    i wrote this simple program and it works but resulting image has color artifacts in it: Source image Result image Expected image

    code:

    package main
    
    import (
        "github.com/nfnt/resize"
        "image"
        _ "image/jpeg"
        "image/png"
        "os"
    )
    
    func main() {
        reader, _ := os.Open("test/1.jpg")
        defer reader.Close()
        m, _, _ := image.Decode(reader)
        m = resize.Resize(32, 32, m, resize.Bicubic)
        file, _ := os.OpenFile("test/1.png", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
        png.Encode(file, m)
        defer file.Close()
    }
    
  • Wrong size of final image after resize

    Wrong size of final image after resize

    I would like to report issue which occurs with some pictures.

    When I resize this image: https://twimg0-a.akamaihd.net/profile_images/2725838700/32f4e2dce13c0b983003eaa10efea6a5.png

    using code

    var m2 image.Image = resize.Resize(60, 60, m1, resize.Lanczos3)

    it does not matter what filter I use, final dimensions are 59x59 and one column and row of pixels is missing at right and bottom. For other images the result is as expected (60x60px).

    I don't know if it is anyhow important, source image is 256x256px.

  • Increased file size after resizing (downscaling)

    Increased file size after resizing (downscaling)

    I've noticed that when images are resized, specifically when they're reduced in size, the resulting file size is larger than the original. I'm not sure if I'm misunderstanding something but I'd expect the file size to decrease with the size of the image.

    width := 10
    height := 10
    
    img, format, err := image.Decode(bytes.NewReader(file))
    if err != nil {
    	return nil, "", err
    }
    //Only resize if new dimensions are specified
    if width != 0 || height != 0 {
    	img = resize.Resize(width, height, img, resize.Lanczos3)
    }
    var buf bytes.Buffer
    switch format {
    case "jpeg":
    	jpeg.Encode(&buf, img, nil)
    case "png":
    	png.Encode(&buf, img)
    case "gif":
    	gif.Encode(&buf, img, nil)
    default:
    	return nil, "", errors.New("not an image")
    }
    
    data := buf.Bytes()
    fmt.Printf("Size: %d", binary.Size(data))
    

    In this case, I'm serving the images from a web server and I've implemented this resizing to decrease request sizes. In one example, the original request with no resizing is 755B. With resizing the image to half its size, the request size is 4.5KB.

    Any suggestions?

  • Add go.mod

    Add go.mod

    Without go.mod, go build and go test fails with error:

    go: cannot find main module, but found .git/config in /work/nfnt-resize
            to create a module there, run:
            go mod init
    

    Since 1.16, golang will build packages in module-aware mode by default, see: https://go.dev/blog/go116-module-changes#modules-on-by-default

  • Adding Power support(ppc64le) with continuous integration/testing to the project for architecture independent

    Adding Power support(ppc64le) with continuous integration/testing to the project for architecture independent

    This is part of the Ubuntu distribution for ppc64le. This helps us simplify testing later when distributions are re-building and re-releasing,For more info tag @gerrith3.

  • I'm no longer updating this package.

    I'm no longer updating this package.

    As it may have been apparent by my long reaction time to PRs and issues, I haven't spend too much time working on this package in the last years. And I plan to keep it that way, hence I won't really look at PRs and issues anymore. Take a look at x/image/draw or gopkg.in/gographics/imagick.v2/imagick for packages that offer image resizing and much more.

A lightning fast image processing and resizing library for Go

govips A lightning fast image processing and resizing library for Go This package wraps the core functionality of libvips image processing library by

Jan 8, 2023
An image resizing server written in Go
An image resizing server written in Go

picfit picfit is a reusable Go server to manipulate images (resize, thumbnail, etc.). It will act as a proxy on your storage engine and will be served

Dec 24, 2022
Image resizing for the Go programming language with common interpolation methods

This package is no longer being updated! Please look for alternatives if that bothers you. Resize Image resizing for the Go programming language with

Dec 14, 2021
Image - This repository holds supplementary Go image librariesThis repository holds supplementary Go image libraries

Go Images This repository holds supplementary Go image libraries. Download/Insta

Jan 5, 2022
Fast and secure standalone server for resizing and converting remote images

imgproxy imgproxy is a fast and secure standalone server for resizing and converting remote images. The main principles of imgproxy are simplicity, sp

Jan 1, 2023
Cloud function + website for resizing, cropping and bordering images for pragalicious.com

Cloud function + website for resizing, cropping and bordering images for pragalicious.com

Jan 23, 2022
Image processing algorithms in pure Go
Image processing algorithms in pure Go

bild A collection of parallel image processing algorithms in pure Go. The aim of this project is simplicity in use and development over absolute high

Jan 6, 2023
Pure Go encoder/decoder of the QOI image format

QOI - The “Quite OK Image” format for fast, lossless image compression package and small utilities in native Go, quite OK implementation See qoi.h for

Nov 12, 2022
darkroom - An image proxy with changeable storage backends and image processing engines with focus on speed and resiliency.
darkroom - An image proxy with changeable storage backends and image processing engines with focus on speed and resiliency.

Darkroom - Yet Another Image Proxy Introduction Darkroom combines the storage backend and the image processor and acts as an Image Proxy on your image

Dec 6, 2022
Easily customizable Social image (or Open graph image) generator

fancycard Easily customizable Social image (or Open graph image) generator Built with Go, Gin, GoQuery and Chromedp Build & Run Simply, Clone this rep

Jan 14, 2022
An API which allows you to upload an image and responds with the same image, stripped of EXIF data

strip-metadata This is an API which allows you to upload an image and responds with the same image, stripped of EXIF data. How to run You need to have

Nov 25, 2021
Imgpreview - Tiny image previews for HTML while the original image is loading
Imgpreview - Tiny image previews for HTML while the original image is loading

imgpreview This is a Go program that generates tiny blurry previews for images t

May 22, 2022
Pure Golang Library that allows simple LSB steganography on images
Pure Golang Library that allows simple LSB steganography on images

Steganography Lib Steganography is a library written in Pure go to allow simple LSB steganography on images. It is capable of both encoding and decodi

Dec 22, 2022
NanoVGo NanoVGNanoVGo is pure golang implementation of NanoVG. The same author maintains the NanoGUI.go project mentioned above.

NanoVGo Pure golang implementation of NanoVG. NanoVG is a vector graphics engine inspired by HTML5 Canvas API. DEMO API Reference See GoDoc Porting Me

Dec 6, 2022
:triangular_ruler: Create beautiful generative image patterns from a string in golang.
:triangular_ruler: Create beautiful generative image patterns from a string in golang.

geopattern Create beautiful generative image patterns from a string in golang. Go port of Jason Long's awesome GeoPattern library. Read geopattern's d

Dec 29, 2022
golang package to find the K most dominant/prominent colors in an image
golang package to find the K most dominant/prominent colors in an image

prominentcolor Find the K most dominant colors in an image The Kmeans function returns the K most dominant colors in the image, ordered in the order o

Nov 7, 2022
An image server toolkit in Go (Golang)
An image server toolkit in Go (Golang)

Image Server An image server toolkit in Go (Golang) Features HTTP server Resize (GIFT, nfnt resize, Graphicsmagick) Rotate Crop Convert (JPEG, GIF (an

Dec 22, 2022
Use Windows API to capture a image from a Webcam in GoLANG

Windows-API-Capture-Webcam Use Windows API to capture a image from a Webcam in GoLANG Other Go is a amazing and powerful programming language. If you

Aug 13, 2022
ColorX is a library to determine the most prominent color in an image written in golang

ColorX is a library to determine the most prominent color in an image. ColorX doesn't use any sort of complex algorithms to calculate the prominent color, it simply loops over the image pixels and returns the color that occurs the most.

Nov 11, 2021