Unsupported clipboard format when pasting PNG/JPG files

Julian

I'm coding a unit where I can paste an image from the clipboard and save it in a DB. The code actually works if I took screenshots or copy images from WhatsApp/Telegram Web.

But the problems appears when I try to paste a PNG or JPG file from the clipboard - the error message is:

Unsupported clipboard format

Why does this code work with screenshots but not with PNG or JPG files? How can I fix it?

BMP := TBitmap.Create;
BMP.Assign(Clipboard);      //Here is where I got the exception
BMP.PixelFormat := pf32bit;
JPG := TJPEGImage.Create;
JPG.Assign(BMP);
JPG.CompressionQuality := 75;
AdvOfficeImage1.Picture.Assign(JPG);
Andreas Rejbrand

If you copy a file from the shell, the clipboard will not contain the contents of the file, but merely the file name.

Hence, you need to obtain this file name, and then use it to load your image.

Here's a small example, just containing a TImage control:

procedure TForm1.FormClick(Sender: TObject);
begin

  if Clipboard.HasFormat(CF_HDROP) then
  begin

    Clipboard.Open;
    try
      var LDrop := Clipboard.GetAsHandle(CF_HDROP);
      if LDrop <> 0 then
      begin
        var LFileCount := DragQueryFile(LDrop, $FFFFFFFF, nil, 0);
        if LFileCount = 1 then
        begin
          var LSize := DragQueryFile(LDrop, 0, nil, 0);
          if LSize <> 0 then
          begin
            var LFileName: string;
            SetLength(LFileName, LSize);
            if DragQueryFile(LDrop, 0, PChar(LFileName), LFileName.Length + 1) <> 0 then
              Image1.Picture.LoadFromFile(LFileName);
          end;
        end;
      end;
    finally
      Clipboard.Close;
    end;

  end;

end;

Note: Clipboard is declared in Clipbrd and DragQueryFile in ShellAPI.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324273041&siteId=291194637