In-memory copy of an arbitrary image.Image

2,050 views
Skip to first unread message

Philipp Schumann

unread,
Feb 14, 2013, 4:40:28 AM2/14/13
to golan...@googlegroups.com
Right now, seems like this is the only way:


Would anyone know of a smarter/better/shorter way? As an aside, wouldn't an image.Image.Clone() method be useful in the standard library?

A really-not-that-exotic use-case: wanting to keep the original image in memory while modifying a copy of it -- without having to load-from-disk-and-image.Decode() the same picture twice.

Philipp Schumann

unread,
Feb 14, 2013, 4:43:17 AM2/14/13
to golan...@googlegroups.com
Apologies for a minor bug in that source -- the Pix slice is allocated a-new in the copy, but not populated with the original pixels.

So yes then in addition to:

copy.Pix = make([]uint8, len(pic.Pix))

everywhere, I'd follow that by:

copy.Pix[:] = pic.Pix[:]

to ensure the contents of the original byte-slice is being copied over...

Doesn't change my original question though!

Philipp Schumann

unread,
Feb 14, 2013, 4:46:02 AM2/14/13
to golan...@googlegroups.com
And of course...  by cloned.Pix[:] = pic.Pix[:]  I  mean: copy(pic.Pix, cloned.Pix)
...

Philipp Schumann

unread,
Feb 14, 2013, 4:48:45 AM2/14/13
to golan...@googlegroups.com
Updated source for this question:


So, finally -- isn't there a smarter way for this functionality?

Nigel Tao

unread,
Feb 14, 2013, 6:28:54 PM2/14/13
to Philipp Schumann, golang-nuts
On Thu, Feb 14, 2013 at 8:40 PM, Philipp Schumann
<philipp....@gmail.com> wrote:
> Would anyone know of a smarter/better/shorter way? As an aside, wouldn't an
> image.Image.Clone() method be useful in the standard library?

When I want to work on a clone, I usually convert to RGBA at the same time:

func CloneToRGBA(src image.Image) draw.Image {
b := src.Bounds()
dst := image.NewRGBA(b)
draw.Draw(dst, b, src, b.Min, draw.Src)
return dst
}

If you must keep the original image type, a type switch is the way to
go. I would write it like http://play.golang.org/p/R7VPM30BBG

P.S. you'll also need to switch on image.YCbCr if you want to clone
the result of decoding JPEGs.

Philipp Schumann

unread,
Feb 14, 2013, 11:21:12 PM2/14/13
to golan...@googlegroups.com, Philipp Schumann
Thanks! Yeah I'm already converting YCbCr and Paletted as the first pre-processing step (prior to this later processing stage where I need a clone and keep the original).

But there I was getting-and-setting all pixels instead of using draw.Draw(), which certainly looks like a better idea  :)

David DENG

unread,
Feb 15, 2013, 1:56:22 AM2/15/13
to golan...@googlegroups.com
What's the operation you'll do to the image? I'd like to convert the loaded Image into data-structures of my own, process, put the result back to an Image and save to disk.

The data-structures could look like this:

type RGB [3]int
type RGBData [][]RGB

type GrayData [][]int

David
Reply all
Reply to author
Forward
0 new messages