![](/img/trans.png)
[英]How to send class which contain Image from Android to Java Restful Web server using Retrofit
[英]Send Image from Android to Datasnap Restful Server
我有一個Android應用程序,使用XE2中的RESTFul客戶端內容將數據發送回datasnap服務器。
我有它可以正常發送標准基本數據,但部分應用程序包括存儲用戶所需的圖像。
我最初嘗試使用TStream,但從未回到服務器 - 它似乎只是掛起。 我目前的想法是將圖像的byte []轉換為base64字符串,然后在datasnap端重新轉換。
要在Android端將圖像轉換為base64字符串,請執行以下操作:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
String encodedString = Base64.encode(stream.toByteArray)
然后, encodedString
作為標准Delphi字符串發送
在服務器端,要解碼的代碼是
function Base64Decode(const EncodedText: string): TBytes;
var
DecodedStm: TBytesStream;
Decoder: TIdDecoderMIME;
begin
Decoder := TIdDecoderMIME.Create(nil);
try
DecodedStm := TBytesStream.Create;
try
Decoder.DecodeBegin(DecodedStm);
Decoder.Decode(EncodedText);
Decoder.DecodeEnd;
Result := DecodedStm.Bytes;
SetLength(Result, DecodedStm.Size); // add this line
finally
DecodedStm.Free;
end;
finally
Decoder.Free;
end;
end;
然后
var
Bytes : TBytes;
image : TJPEGImage;
stream : TBytesStream;
begin
Bytes := Base64Decode(Photo);
stream := TBytesStream.Create(Bytes);
image := TJPegImage.Create;
image.LoadFromStream(stream);
這會在loadFromStream
方法中創建一個錯誤,基本上jpeg已損壞。 我猜測然后編碼(不太可能)或轉換為delphi字符串然后解碼為byte [](可能)有問題。
因此,如果有人對如何將圖像從Android應用程序發送到Delphi XE2中的DataSnap服務器有任何建議,這是一個冗長的方式?
uses
DBXJSONCommon,
function TServerImageMethods.ConvertJPEGToJSon(pFilePath: string): TJSONArray;
var
AFileStream: TFileStream;
begin
AFileStream := TFileStream.Create(pFilePath, fmOpenRead);
Result := TDBXJSONTools.StreamToJSON(AFileStream, 0, AFileStream.Size);
end;
我轉換回TStream:
AFileStream := TDBXJSONTools.JSONToStream(JSONArray);
PS。:您可以使用ZLIB壓縮流以獲得最佳性能。
我正在加載JPEG圖像,但我將指針設置在開頭,並配置圖像:
stream.Seek(0,soFromBeginning);
image.PixelFormat := jf24Bit;
image.Scale := jsFullSize;
image.GrayScale := False;
image.Performance := jpBestQuality;
image.ProgressiveDisplay := True;
image.ProgressiveEncoding := True;
image.LoadFromStream(stream);
If stream.size > 0 then
// OK
else
// not OK
我還將嘗試解碼ANSIString,以檢查它是否與Unicode更改有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.