如何用JPG或PNG制作缩略图并将其加载到Timage控件中?

时间:2019-03-03 06:08:16

标签: png jpeg thumbnails delphi-10.2-tokyo timage

如何从JPG或PNG制作缩略图并将该缩略图加载到TImage控件中?

我已经尝试过类似的操作,但是TImage看起来好像不是正在加载某些东西。

Image2TImage控件。

function resize2(source: string): TBitmap;
var
  BMPFile, ScreenBMP: TBitmap;
begin
  BMPFile := TBitmap.Create;
  try
    BMPFile.LoadFromFile(source);
    ScreenBMP := TBitmap.Create;
    ScreenBMP.PixelFormat := BMPFile.PixelFormat;
    ScreenBMP.Width := 10;
    ScreenBMP.Height := 10;
    ScreenBMP.Canvas.StretchDraw(Rect(0,0, ScreenBMP.Width, ScreenBMP.Height), BMPFile);
    Result := ScreenBMP;
  finally
    BMPFile.Free;
  end;
end;

procedure TAlpha.dbeditTextBoxChange(Sender: TObject);
var
  pic1: string;
  mimapa: TBitmap;
begin
  try
    pic1 := dm.TableNotes.FieldByName('PathPic').AsVariant;
    mimapa := resize2(pic1);

    //all of these are not working
    Image2.Assign(mimapa);
    image2.Picture.Bitmap := mimapa;

1 个答案:

答案 0 :(得分:2)

VCL的TBitmap仅支持BMP图像。如果尝试将任何其他类型的图像加载到其中,则会引发异常。

要加载JPG,您需要改用TJPEGImage。要加载PNG,请改用TPNGImage

您可以使用TPicture来帮助您完成该任务,例如:

uses
 ..., Vcl.Graphics, Vcl.Imaging.jpeg, Vcl.Imaging.pngimage;

function resize2(source: string): TBitmap;
var
  Pic: TPicture;
begin
  Pic := TPicture.Create;
  try
    Pic.LoadFromFile(source);
    Result := TBitmap.Create;
    try
      if Pic.Graphic is TBitmap then
        Result.PixelFormat := TBitmap(Pic.Graphic).PixelFormat
      else
        Result.PixelFormat := pf32bit;
      Result.Width := 10;
      Result.Height := 10;
      Result.Canvas.StretchDraw(Rect(0, 0, Result.Width, Result.Height), Pic.Graphic);
    except
      Result.Free;
      raise;
    end;
  finally
    Pic.Free;
  end;
end;

procedure TAlpha.dbeditTextBoxChange(Sender: TObject);
var
  pic1: string;
  mimapa: TBitmap;
begin
  try
    pic1 := dm.TableNotes.FieldByName('PathPic').AsString;
    mimapa := resize2(pic1);
    try
      image2.Picture.Assign(mimapa);
    finally
      mimapa.Free;
    end;
    ...
  except
   ...
  end;
end;