canvas: drawImage has size error after image.bounds was modified

I’m adding crop feature now, and found a strange case.

At first, here is my code, I used module “github.com/oliamb/cutter” @see the doc here, if you need

croppedImg, _ := cutter.Crop(img, cutter.Config{
	Width:  i.Clip.Width,
	Height: i.Clip.Height,
	Anchor: image.Point{i.Clip.X, i.Clip.Y},
})
img = croppedImg

// omitted some code, it doesn't matter
c.DrawImage(x, y, img, scale)

The image size was 430 * 430, I crop it, from startPos(30, 30) to (400, 400). after I doing this, img.Bounds() will lead to (30,30)-(400,400). this could be reason about the case.

image

So, I save the image to local. here is anthoer test,if I do this. the img.bounds() will be (0,0)-(370,370), and result is fine.

croppedImg, _ := cutter.Crop(img, cutter.Config{
	Width:  i.Clip.Width,
	Height: i.Clip.Height,
	Anchor: image.Point{i.Clip.X, i.Clip.Y},
})
img = croppedImg

f, err := os.Create("test_crop.jpg")
if err != nil {
	panic(err)
}
defer f.Close()
jpeg.Encode(f, img, nil)

// omitted some code, it doesn't matter
c.DrawImage(x, y, img, scale)

image

I’ve tried find reason about this, include try another crop image service from aliyun. but it shows similarity.

Here is some code from module “github.com/oliamb/cutter”, I thinks it’s normal implementation.

func Crop(img image.Image, c Config) (image.Image, error) {
	maxBounds := c.maxBounds(img.Bounds())
	size := c.computeSize(maxBounds, image.Point{c.Width, c.Height})
	cr := c.computedCropArea(img.Bounds(), size)
	cr = img.Bounds().Intersect(cr)

	if c.Options&Copy == Copy {
		return cropWithCopy(img, cr)
	}
	if dImg, ok := img.(subImageSupported); ok {
		return dImg.SubImage(cr), nil
	}
	return cropWithCopy(img, cr)
}

Thanks.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 16 (8 by maintainers)

Most upvoted comments

Ok, apparently there was another bug as well.

Can you try with the latest version of my fix?

replace github.com/tdewolff/canvas => github.com/oliverpool/canvas v0.0.0-20200414143817-2158c3b733b4

Yes, SavePNG is legacy, you should now use c.WriteFile.

For instance (taken from https://github.com/tdewolff/canvas/blob/master/examples/preview/main.go)

c.WriteFile("out.png", rasterizer.PNGWriter(5.0))