Home
What's New
Delphi 3.0 Tips
Questions
Development Tools
Links

Conversion between a Bitmap and a JPEG


//you must include jpeg in your uses clause

{this function loads a bitmap named fName from disk 
 and saves it as a jpeg by the same name; it returns 
 true if successful and false otherwise; a similiar 
 function will convert a JPEG to a BitMap}
function TForm1.BitMapToJPEG (fName : TFileName) : boolean;
var
  BitMap : TBitMap;
  JPEGImage : TJPEGImage;
begin
  result := FileExists (fName); 
  if not result then exit;

  BitMap := TBitMap.Create;

  //ChangeExt is writen out below
  fName := ChangeExt (fName, 'bmp');

  BitMap.LoadFromFile (fName);
  fName := ChangeExt (fName, 'jpg');

  if FileExists (fName) then
    if MessageDlg ('"' + fName + '" exists. Overwrite?',
                   mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin
      BitMap.free;
      result := false;
      exit;
    end;

  JPEGImage := TJPEGImage.Create;

  //90 is arbitrary
  JPEGImage.CompressionQuality := 90;

  JPEGImage.Assign (BitMap);
  JPEGImage.SaveToFile (fName);

  BitMap.Free;
  JPEGImage.Free;
end;

{change the extension of fName to whatever ext is; 
 if fName has no extension, then ext is appended to it}
function ChangeExt (const fName, ext : TFileName) : TFileName;
var i : cardinal;
begin
  i := posE ('.', fName);
  if i > 0 then
    result := copy (fName, 1, i - 1)
  else
    result := fName;

  if (ext <> '') and (ext[1] <> '.') then
    result := result + '.' + ext
  else
    result := result + ext;
end;