clipboard icon indicating copy to clipboard operation
clipboard copied to clipboard

Windows: Write an image encoded to PNG after being loaded as JPEG messes up the image

Open matwachich opened this issue 2 years ago • 6 comments

package main

import (
	"bytes"
	"image"
	"image/png"
	"os"

	"golang.design/x/clipboard"

	_ "image/jpeg"
)

func main() {
	if err := clipboard.Init(); err != nil {
		panic(err)
	}

	// open some jpeg file
	fh, err := os.Open("image.jpg")
	if err != nil {
		panic(fh)
	}
	defer fh.Close()

	// decode the jpeg
	img, _, err := image.Decode(fh)
	if err != nil {
		panic(err)
	}

	// re-encode it to png
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		panic(err)
	}

	// image copied to clipboard is totally messed up
	clipboard.Write(clipboard.FmtImage, buf.Bytes())

	// image saved to file is good
	wfh, err := os.Create("image.png")
	if err != nil {
		panic(err)
	}
	defer wfh.Close()

	wfh.Write(buf.Bytes())
}

When executing this on windows, the PNG on disk is good, but the one on clipboard is bad

Source JPEG 508118

Here is the resulting PNG in clipboard image

matwachich avatar Jun 07 '23 22:06 matwachich

According to the doc of Write: Write writes a given buffer to the clipboard in a specified format. Write returned a receive-only channel can receive an empty struct as a signal, which indicates the clipboard has been overwritten from this write. If format t indicates an image, then the given buf assumes the image data is PNG encoded.

changkun avatar Jun 08 '23 05:06 changkun

Euh yes, I don't understand yet what I did wrong in my code.

I decode a jpeg into an image.Image, then I re-encode it to PNG in a bytes.Buffer, and I write this buffer to the clipboard and to a file to compare.

The written file is good, but clipboard's content is screwed.

matwachich avatar Jun 09 '23 13:06 matwachich

Which clipboard receiver are you using on Windows? Are you using the system built-in clipboard? (On Windows, use Shift+Win+s) I remember from Windows; it might be problematic because there is an implicit agreement between the content writer and content receiver.

changkun avatar Jun 09 '23 13:06 changkun

I just past clipboard content inside paint.exe. I don't use any non standard clipboard.

I think the implicit agrement is that the data is a PNG encoded data/file?

matwachich avatar Jun 10 '23 09:06 matwachich

I experience the same issue, no matter what image I use, and if it's png encoded or not, the final image which I paste from the clipboard is corrupt. if I write it to file instead, the image is normal png image. I guess that windows expects for BMP and not PNG or someting like that.

thewh1teagle avatar Feb 25 '24 00:02 thewh1teagle