Delphi 2010
我通过自定义TCP套接字控件传输图像使用UTF-8
客户端
var
TSS: TStringStream;
STR :String;
JPG:TJPEGImage;
BMP:TBitmap;
begin
Try
BMP.LoadFromFile('C:\1.bmp');
JPG.Assign(BMP);
JPG.CompressionQuality:=80;
JPG.Compress;
TSS:=TStringStream.Create;
JPG.SaveToStream(TSS);
STR:=TSS.DataString;
MyTCPSocket.SendString(STR);
finally
BMP.free;
JPG.free;
TSS.free;
end;
end;
服务器端
Var
TSS: TStringStream;
TSS:=TStringStream.Create;
TSS.WriteString(STR);
TSS.SaveToFile('C:\2.jpg');
这段代码工作在同一台电脑上很棒。
将图像发送到使用不同编码的其他电脑时的问题 它收到图像,但我在数据“?????”中看到许多错误的字符
我认为当TStringStream将字节写入文件时,它无法将unicode字符转换为字节,因此它看起来像“?”
非常感谢任何想法
答案 0 :(得分:5)
您正在尝试发送二进制数据,就好像它是UTF-8编码的文本一样。 不是,所以不要试图这样做!以原始二进制形式发送二进制数据,例如:
var
MS: TMemoryStream;
JPG: TJPEGImage;
BMP: TBitmap;
begin
MS := TMemoryStream.Create;
try
JPG := TJPEGImage.Create;
try
BMP := TBitmap.Create;
try
BMP.LoadFromFile('C:\1.bmp');
JPG.Assign(BMP);
finally
BMP.Free;
end;
JPG.CompressionQuality := 80;
JPG.Compress;
JPG.SaveToStream(MS);
finally
JPG.Free;
end;
MS.Position := 0;
MyTCPSocket.SendStream(MS);
finally
MS.free;
end;
end;
var
MS: TMemoryStream;
begin
MS := TMemoryStream.Create;
try
MyTCPSocket.ReadStream(MS);
MS.Position := 0;
MS.SaveToFile('C:\2.jpg');
finally
MS.Free;
end;
end;
如果必须将二进制数据作为文本发送,则需要使用真正的二进制到文本编码算法对数据进行编码,例如base64或yEnc,不 UTF-8(设计为仅用于编码Unicode文本,而不是二进制数据),例如:
// TIdEncoderMIME and TIdDecoderMIME are part of Indy,
// which ships with Delphi, but you can use whatever
// you want...
uses
..., IdCoderMIME;
var
S: String;
MS: TMemoryStream;
JPG: TJPEGImage;
BMP: TBitmap;
begin
MS := TMemoryStream.Create;
try
JPG := TJPEGImage.Create;
try
BMP := TBitmap.Create;
try
BMP.LoadFromFile('C:\1.bmp');
JPG.Assign(BMP);
finally
BMP.Free;
end;
JPG.CompressionQuality := 80;
JPG.Compress;
JPG.SaveToStream(MS);
finally
JPG.Free;
end;
MS.Position := 0;
S := TIdEncoderMIME.EncodeStream(MS);
finally
MS.free;
end;
MyTCPSocket.SendString(S);
end;
uses
..., IdCoderMIME;
var
S: string;
MS: TMemoryStream;
begin
S := MyTCPSocket.ReadString;
MS := TMemoryStream.Create;
try
TIdDecoderMIME.DecodeStream(S, MS);
MS.Position := 0;
MS.SaveToFile('C:\2.jpg');
finally
MS.Free;
end;
end;