golang-design / clipboard

📋 cross-platform clipboard package that supports accessing text and image in Go (macOS/Linux/Windows/Android/iOS)
https://golang.design/x/clipboard
MIT License
579 stars 64 forks source link

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

Open matwachich opened 1 year ago

matwachich commented 1 year ago
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

changkun commented 1 year ago

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.

matwachich commented 1 year ago

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.

changkun commented 1 year ago

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.

matwachich commented 1 year ago

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?

thewh1teagle commented 6 months ago

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.