可以把常见的图片格式一律转成JPG流的函数,改进一下就可以达到你的要求,要引用JPEG及tGifImage(网上有很多下载的,如不需要,去除即可)
Procedure AnyToJpg(Const FileName:String; var JpgStream:TMemoryStream; MaxSize:Integer);
var tpPic:TImage;
tpJpg:TJpegImage;
tpGif:TGifImage;
tpBmp:TBitMap;
TpStream:TMemoryStream;
tpRatio
![Big Grin :D :D](https://cdn.jsdelivr.net/joypixels/assets/8.0/png/unicode/64/1f600.png)
ouble;
tpSize,tpWidth,tpHeight:Integer;
begin
//不管什么图片,一律转成JPG保存
if Not FileExists(FileName) then begin
JpgStream:=Nil;
Exit;
end;
try
tpPic:=tImage.Create(nil);
tpJpg:=TJpegImage.create;
tpGif:=TGifImage.Create;
tpBmp:=TBitmap.Create;
if Pos('.GIF',UpperCase(FileName))>0 then
begin
tpGif.LoadFromFile(FileName);
tpBmp.Assign(tpGif.Bitmap);
tpPic.Picture.Assign(tpBmp);
end
else
tpPic.Picture.LoadFromFile(FileName);
if Assigned(tpPic.Picture) then
tpJpg.Assign(tpPic.Picture.Graphic)
else
tpJpg.Assign(nil);
tpStream:=TMemoryStream.Create;
tpJpg.SaveToStream(tpStream);
tpStream.Position:=0;
if MaxSize<=0 then
jpgStream:=tpStream
else
begin
//查看jpg图的尺寸是否超标,如超标,则自动缩成指定大小
tpSize:=tpStream.Size;
if tpSize > MaxSize*1024 then //好像还不行,再说
begin
ShowMessage('Image "'+FileName+'" Size Over than Max Size:'+Trim(IntToStr(MaxSize))+' KB');
JpgStream:=Nil;
Exit;
{ //把JPG自动压缩成指定大小,可惜没做到
tpRatio:= RoundFloat(Sqrt(tpSize / (MaxSize * 1024)),6);
tpWidth:=Round(tpJpg.Width / tpRatio);
tpHeight:=Round(tpJpg.Height / tpRatio);
tpJpg.Performance:=jpBestSpeed;
tpjpg.CompressionQuality:=50;
tpJpg.JPEGNeeded;
tpJpg.Compress;
if not Assigned(JpgStream) then
JpgStream:=TMemoryStream.Create;
ZoomPic(tpStream,tpWidth,tpHeight,jpgStream);
tpJpg.CompressionQuality:=20;
tpJpg.JPEGNeeded;
tpJpg.Compress;
tpJpg.SaveToStream(tpStream);
JpgStream:=tpStream; }
end
else
jpgStream:=tpStream;
end;
JpgStream.Position:=0;
finally
tpPic.Free;
tpJpg.Free;
tpGif.Free;
tpBmp.Free;
end;
end;