Convert a Bitmap Image to a Jpeg Image

vegaseat 0 Tallied Votes 1K Views Share

A data stream is used to load a bitmap image and convert it to a jpeg image. The converted image is displayed and saved to a .jpg file.

{------------------------------------------------------------------------
  Load a .bmp image, convert to a .jpg image, display and save as .jpg 
  Need to use stream to save as jpeg file, since the usual
  Image.Picture.SaveToFile(FileName)  would save image as bitmap file.
  Delphi 3.0  by  vegaseat
-------------------------------------------------------------------------}

unit BMP2JPGz;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls, Jpeg;

type
  TForm1 = class(TForm)
    Image1: TImage;
    LoadPictureButton: TButton;
    Image2: TImage;
    Label1: TLabel;
    Label2: TLabel;
    SaveJPGButton: TButton;
    procedure LoadPictureButtonClick(Sender: TObject);
    procedure SaveJPGButtonClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

procedure ConvertBMP2JPG(Instream: TStream);

implementation

{$R *.DFM}

procedure ConvertBMP2JPG(Instream: TStream);
var
  JpegImage: TJpegImage;
  Bitmap: TBitmap;
begin
  JpegImage := TJpegImage.Create;
  Bitmap := TBitmap.Create;
  try
    // Load and display the bitmap image
    Bitmap.LoadFromStream(InStream);
    Form1.Image1.Canvas.Draw(0,0,Bitmap);
    Form1.Label1.Caption := 'Bitmap picture';
    // convert to jpeg and display
    JpegImage.Assign(Bitmap);
    Form1.Image2.Canvas.Draw(0,0,JpegImage);
    Form1.Label2.Caption := 'Jpeg picture';
  finally
    JpegImage.Free;
    Bitmap.Free;
  end;
end;

procedure TForm1.LoadPictureButtonClick(Sender: TObject);
var
  InStream: TFileStream;
begin
  try
    // change to whatever bitmap file you have ...
    InStream := TFileStream.Create('Naomi.bmp',fmOpenRead);
    ConvertBMP2JPG(Instream);
  finally
    InStream.Free;
  end;
end;

procedure TForm1.SaveJPGButtonClick(Sender: TObject);
var
  OutStream: TFileStream;
  JpegImage: TJpegImage;
begin
  JpegImage := TJpegImage.Create;
  JpegImage.Assign(Image2.Picture.Bitmap);
  try
    OutStream := TFileStream.Create('Naomi.jpg',fmOpenWrite or fmCreate);
    JpegImage.SaveToStream(OutStream);
  finally
    OutStream.Free;
  end;
  JpegImage.Free;
end;

end.