如何正确地将 Timage 位图分配给 jpg?

how do i Assigning Timage bitmap to jpg correctly?

我正在执行以下操作以调整 Timage 图形的大小并将其另存为 jpg 。图片保存为空白。

这是我如何分配 Timage

begin
 with TOpenDialog.Create(self) do
    try
      Caption := 'Open Image';
      Options := [ofPathMustExist, ofFileMustExist];
      Filter  := 'JPEG Image File (*.jpg)|*.jpg|JPEG Image File (*.jpeg)|*.jpeg|Bitmaps (*.bmp)|*.bmp';
      if Execute then
        image1.Picture.LoadFromFile(FileName);
    finally
      Free;
    end;
end;

下面是我调整 timage 大小并将其分配到 jpg 中的方法。

 with Image2.Canvas do begin
    Lock;
    try
      try
        Image2.Picture.Graphic.Width := 50;
        Image2.Picture.Graphic.Height := 50;
        FillRect(ClipRect);
        StretchDraw(rect(0, 0, 50, 50), image1.Picture.Bitmap);
      except
        on E: Exception do
//log

      end;
    finally
      Unlock;
    end;
  end;




Jpg := TJPEGImage.Create;
try

Jpg.Performance := jpBestSpeed;
Jpg.ProgressiveEncoding := True;
Jpg.ProgressiveDisplay := True;
Jpg.Assign(image2.Picture.Bitmap);
Jpg.CompressionQuality := 90;
Jpg.Compress;
jpg.SaveToFile('screena.jpg');



finally
Jpg.Free;
end;

保存的jpg变成空白我做错了什么?我需要做的就是将图像从磁盘加载到 Timage,然后调整宽度和高度并将其再次分配到 jpg

您的图像为空白的原因是因为您在将 Image1 绘制到 Image2 的 canvas 上时使用了 Picture.Bitmap 属性:

StretchDraw(rect(0, 0, 50, 50), image1.Picture.Bitmap);

如果您没有将 .bmp 文件加载到 Image1,访问 Bitmap 属性 将清除当前图像并将其替换为空白图像。这是 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.

TCanvas.StretchDraw() 方法在其第三个参数中接受任何 TGraphic 对象。您应该传入 Picture.Graphic 属性 而不是 Picture.Bitmap 属性:

StretchDraw(rect(0, 0, 50, 50), image1.Picture.Graphic);

旁注:分配 TOpenDialog.Filter 属性 时,请考虑在 Graphics 单元中使用 VCL 的 GraphicFilter() 函数:

Returns a file filter compatible with the Filter property of an Open or Save dialog.

Call GraphicFilter to obtain a value for the Filter property of an Open, Open Picture, Save Picture or Save dialog box. The GraphicClass parameter can specify one of these values: TBitmap, TGraphic, TIcon, TMetafile, or a user-defined descendant of TGraphic.

例如:

Filter := GraphicFilter(TGraphic);

如果您要手动填充 Filter,那么至少不要为不同的 JPEG 扩展名设置单独的条目。将它们组合在一个条目中,例如:

Filter  := 'JPEG Images (*.jpg, *.jpeg)|*.JPG;*.JPEG|Bitmap Images (*.bmp)|*.BMP';