Load a JPG in a TImage, preserving the aspect ratio (Views: 29)
Problem/Question/Abstract: Load a JPG preservind the original aspect ratio of the JPG. Answer: procedure TForm1.Button1Click(Sender: TObject); procedure CargaJPGProporcionado(Fichero: string; const QueImage: TImage); var ElJPG: TJpegImage; Rectangulo: TRect; EscalaX, EscalaY, Escala: Single; begin ElJPG := TJPegImage.Create; try ElJPG.LoadFromFile(Fichero); //Por defecto, escala 1:1 EscalaX := 1.0; EscalaY := 1.0; //Hallamos la escala de reducción Horizontal if QueImage.Width < ElJPG.Width then EscalaX := QueImage.Width / ElJPG.Width; //La escala vertical if QueImage.Height < ElJPG.Height then EscalaY := QueImage.Height / ElJPG.Height; //Escogemos la menor de las 2 if EscalaY < EscalaX then Escala := EscalaY else Escala := EscalaX; //Y la usamos para reducir el rectangulo destino with Rectangulo do begin Right := Trunc(ElJPG.Width * Escala); Bottom := Trunc(ElJPG.Height * Escala); Left := 0; Top := 0; end; //Dibujamos el bitmap con el nuevo tama?o en el TImage destino with QueImage.Picture.Bitmap do begin Width := Rectangulo.Right; Height := Rectangulo.Bottom; Canvas.StretchDraw(Rectangulo, ElJPG); end; finally ElJPG.Free; end; end; {De CargaJPGProporcionado} begin CargaJPGProporcionado('UnaFoto.jpg', Image1); end; |