Easily Use A Popular Python Image Library In A Delphi Windows GUI App
procedure TForm1.Button2Click(Sender: TObject);
var
_im : Variant;
_stream : TMemoryStream;
_dib : Variant;
pargs: PPyObject;
presult :PPyObject;
P : PAnsiChar;
Len : NativeInt;
begin
if (Image1.Picture.Graphic = nil) or Image1.Picture.Graphic.Empty then
raise Exception.Create(‘You must first select an image’);
PythonEngine1.ExecStrings(Memo1.Lines);
_im := MainModule.ProcessImage(ImageToPyBytes(Image1.Picture.Graphic));
if not chkUseDC.Checked then
begin
// We have to call PyString_AsStringAndSize because the image may contain zeros
with GetPythonEngine do begin
pargs := MakePyTuple([ExtractPythonObjectFrom(_im)]);
try
presult := PyEval_CallObjectWithKeywords(
ExtractPythonObjectFrom(MainModule.ImageToBytes), pargs, nil);
try
if (P = nil) or (PyBytes_AsStringAndSize(presult, P, Len) 0) then begin
ShowMessage(‘This does not work and needs fixing’);
Abort;
end;
finally
Py_XDECREF(pResult);
end;
finally
Py_DECREF(pargs);
end;
end;
_stream := TMemoryStream.Create();
try
_stream.Write(P^, Len);
_stream.Position := 0;
Image1.Picture.Graphic.LoadFromStream(_stream);
finally
_stream.Free;
end;
end
else
begin
Image1.Picture.Bitmap.SetSize(Image1.Width, Image1.Height);
_dib := Import(‘PIL.ImageWin’).Dib(_im);
Image1.Picture.Bitmap.SetSize(Image1.Height, Image1.Width);
_dib.expose(NativeInt(Image1.Picture.Bitmap.Canvas.Handle));
end;
end;