Soon Santos
Soon Santos

Reputation: 2239

Photo is saved to datasnap only in .jpg but not in .png

I am sending a photo to the server using Datasnap by encoding it to base64 with the code below:

My Application Code

Converts the image to base64 and send to the server in Json format.

Memoria := TMemoryStream.Create;
Imagem.Picture.Bitmap.SaveToStream(Memoria);
Memoria.Position := 0;
StrEnv := TStringStream.Create;
TNetEncoding.Base64.Encode(Memoria, StrEnv);
StrEnv.Position := 0;
JOImagem := TJSONObject.Create;
JOImagem.AddPair('photo', StrEnv.DataString);

Datasnap Server

Get the base64 image and save it as a jpg image.

lInStream := TStringStream.Create(JsonObj.GetValue('photo').Value);
lInStream.Position := 0;
lOutStream := TMemoryStream.Create;
TNetEncoding.Base64.Decode(lInStream, lOutStream);
lOutStream.Position := 0;
lOutStream.SaveToFile('photo-name' + '.jpg');

Case 1.

The image is saved successfully if I take the picture directly from my webcam.

Case 2.

If I take a .png or .jpg photo from the computer (using OpenPictureDialog) and save it. It is saved but when I open it says:

We don't support this file format.

Problem

It just works if I take the picture using the webcam, it doesn't work if I get it from the computer.

Upvotes: 0

Views: 149

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598319

Accessing the TImage.Picture.Bitmap property forces the picture to hold a BMP image (wiping out any current non-BMP image). This is documented behavior:

Use Bitmap to reference the picture object when it contains a bitmap. If Bitmap is referenced when the picture contains a Metafile or Icon graphic, the graphic won't be converted (Types of Graphic Objects). Instead, the original contents of the picture are discarded and Bitmap returns a new, blank bitmap.

As such, calling Bitmap.SaveToStream() will NEVER save to any format other than BMP.

If you load any format other than a BMP into the Picture, and want to preserve that format when accessing and saving the image, you need to use the Picture.Graphic property instead of the Picture.Bitmap property, eg:

Imagem.Picture.Graphic.SaveToStream(Memoria);

Upvotes: 1

Related Questions